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:
這道題目還是比較簡(jiǎn)單的浅浮。一開始想用循環(huán)或者遞歸,但題意不要求這么做芥映,要 O(1)的復(fù)雜度洲尊。于是仔細(xì)研究了下,果然有規(guī)律可循奈偏。
**
總結(jié): 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;
}
}
一開始這么寫的坞嘀。
后來找到了規(guī)律,這么寫:
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