Iterate through each digit in a number

Assuming the number is an integer to begin with:

int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;

for (int i = 0; i < strLength; ++i) {
  int digit = Integer.parseInt(strNum.charAt(i));
  sum += (digit * digit);
}

You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.

long addSquaresOfDigits(int number) {
    long result = 0;
    int tmp = 0;
    while(number > 0) {
        tmp = number % 10;
        result += tmp * tmp;
        number /= 10;
    }
    return result;
}

You could also put it in a string and turn that into a char array and iterate through it doing something like Math.pow(charArray[i] - '0', 2.0);


I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo

  public static ArrayList<Integer> splitViaString(long number) {

    ArrayList<Integer> result = new ArrayList<>();
    String s = Long.toString(number);

    for (int i = 0; i < s.length(); i++) {
      result.add(s.charAt(i) - '0');
    }
    return result; // MSD at start of list
  }

vs

  public static ArrayList<Integer> splitViaModulo(long number) {

    ArrayList<Integer> result = new ArrayList<>();

    while (number > 0) {
      int digit = (int) (number % 10);
      result.add(digit);
      number /= 10;
    }
    return result; // LSD at start of list
  }

Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)

So not a lot in it really, but I was a bit surprised that String was faster