渣渣写LEETCODE——258. Add Digits

来源:互联网 发布:java连接redis 编辑:程序博客网 时间:2024/06/01 08:31

Problem:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

Solution:

用模10取出个位,用除10丢掉个位。

O(1)的解法想出来再补充。

Code:

/*__xz__*/class Solution {public:    int addDigits(int num) {        int result = 0;    if (num < 10) return num;    else {    while (num != 0) {    result += num%10;    num /= 10;    }    }        return result;    }};



0 0
原创粉丝点击