Leon Horka Leon Horka - 7 months ago 54
Java Question

Java - How to split an integer into individual digits and then square each number?

So, I want to split an integer into digits and then raise each number to the power 2 and print out that, but this is what I have:

int n = 666;
String number = String.valueOf(n);
for(int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
Math.pow(j, 2);
System.out.println(j);


The output is only the
666
number.

What is it I'm doing wrong?

Answer

Your code isn't working because you don't actually use the return value of Math.pow().

Math.pow(x, 2) is one way to raise a number to the power of 2, but it is floating-point math, not integer math. Power of 2 means to multiply the number by itself, so x * x is much better.

int number = 299792458; // Speed of light in m/s
for (char ch : Integer.toString(number).toCharArray()) {
    int digit = ch - '0';
    System.out.println(digit * digit);
}

Or using Java 8 streams:

int number = 299792458; // Speed of light in m/s
Integer.toString(number)
       .chars()
       .map(c -> (c - '0') * (c - '0'))
       .forEach(System.out::println);

OUTPUT

4
81
81
49
81
4
16
25
64