My code:
public class Solution {
public int addDigits(int num) {
if (num < 0)
return 0;
else if (num < 10)
return num;
else
return (num - 10) % 9 + 1;
}
}
My test result:
这道题目还是比较简单的。一开始想用循环或者递归,但题意不要求这么做,要 O(1)的复杂度。于是仔细研究了下,果然有规律可循。
**
总结: Math
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int addDigits(int num) {
if (num <= 0) {
return num;
}
while (num >= 10) {
num = transfer(num);
}
return num;
}
private int transfer(int num) {
String s = String.valueOf(num);
int sum = 0;
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
sum += (int) (curr - 48);
}
return sum;
}
}
一开始这么写的。
后来找到了规律,这么写:
My code:
public class Solution {
public int addDigits(int num) {
if (num <= 0) {
return num;
}
return num % 9 == 0 ? 9 : num % 9;
}
}
题目没什么难的。
Anyway, Good luck, Richardo! -- 08/27/2016