最短的代码是 -
int compute(int n){
while(n > 9){
n = n - 9;
}
return n;
}
其中 n 是您要计算其某些数字的数字。
编辑:仅对小数字有效,例如 3 位数字。
编辑:测试了几个答案:
public class Test {
public static void main(String [] args){
int i = 0x0fefefef;
long st1 = System.nanoTime();
int n1 = sumDigit(i);
long t1 = System.nanoTime() - st1;
long st2 = System.nanoTime();
int n2 = FindSumDigit(i);
long t2 = System.nanoTime() - st2;
long st3 = System.nanoTime();
int n3 = compute(i);
long t3 = System.nanoTime() - st3;
long st4 = System.nanoTime();
int n4 = compute1(i);
long t4 = System.nanoTime() - st4;
System.out.println("Tested for: "+i);
System.out.println(n1+": "+t1);
System.out.println(n2+": "+t2);
System.out.println(n3+": "+t3);
System.out.println(n4+": "+t4);
}
public static int sumDigit(int n){
int sum = n % 9;
if(sum == 0){
if(n > 0)
return 9;
}
return sum;
}
public static int FindSumDigit(int n)
{
if (n < 10) return n;
int sum = 0;
while (n > 0)
{
sum += n % 10;
n = n / 10;
}
return FindSumDigit(sum);
}
public static int compute( int n ) {
return n - 9 * ((n - 1) / 9);
}
public static int compute1(int n){
while(n > 9){
n = n - 9;
}
return n;
}
}
这是上述测试的结果:
Tested for: 267382767
3: 2432
3: 1621
3: 810
3: 5354519