This uses a direct method and doesn’t feel difficult.
/**
* Created by weixuan on 16/6/5.
*/
public class Test {
// 第一步 to char
public static char[] toChar(Integer data) {
String value = String.valueOf( data );
return value.toCharArray();
}
// 相加
public static Integer add(char[] data) {
Integer sum = 0;
for (char d : data) {
sum += d - '0';
}
return sum;
}
// 判断是否大于9
public static Integer isBiggerCore(Integer data) {
return add( toChar( data ) );
}
public static Integer isBigger(Integer data) {
int value = data;
int temp = isBiggerCore( data );
while (temp > 9) {
value = temp;
temp = isBiggerCore( value );
}
return value;
}
// 987 -> 24
// 99 -> 18
// 199 -> 10
public static void main(String[] args) {
System.out.println(isBigger( 987 ));
}
}
Just output the number modulo 9
Proof:
Suppose the number is:
$$m=a_na_{n-1}ldots a_0$$
then
$$m=sum^n_{i=0}a_itimes10^i$$
$$=sum^n_{i=0}a_itimes(99dots9+1)$$
$$equivsum^n_{i=0}a_i (mod 9)$$
This is the original question on leetcode...
Just take the modulo of 9
This uses a direct method and doesn’t feel difficult.