The shortest code for this is
int compute(int n){ while(n > 9){ n = n - 9; } return n; }
where n is the number for which you want to calculate some of its digits.
EDIT: effective only for small numbers, such as a three-digit number.
EDIT: Several answers tested:
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; } }
Here is the result for the test:
Tested for: 267382767 3: 2432 3: 1621 3: 810 3: 5354519
source share