标签:nbsp tom out its style mod while 数位 col
Given a non-negative integernum
, repeatedly add all its digits until the result has only one digit.
For example:
Givennum = 38
, the process is like:3 + 8 = 11
,1 + 1 = 2
. Since2
has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
题目让求各个数位的和,直到和小于10为止,
直观的想法就是直接相加,先想一下如何求各数位的和
while(num != 0) { tmp += num % 10; num /= 10; }
class Solution { public int addDigits(int num) { while(num / 10 > 0) { int sum = 0; ////注意定义变量的位置 while(num != 0) { sum += num % 10; num /= 10; } num = sum; } return num; } }
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 1
11 2
12 3
13 4
14 5
15 6
16 7
17 8
18 9
19 1
20 2
class Solution { public: int addDigits(int num) { return (num - 1) % 9 + 1; //周期第一位为1,若为2 则 + 2 } };
标签:nbsp tom out its style mod while 数位 col
原文地址:http://www.cnblogs.com/wxshi/p/7598402.html