The Grumpy Lion
The Grumpy Lion

Reputation: 173

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

I want to split an integer into digits and then raise each number to the power 2 and print that out. 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?

Upvotes: 1

Views: 9751

Answers (4)

Alireza Mohamadi
Alireza Mohamadi

Reputation: 521

int m = n;
while (m > 0)
{
    int digit = m % 10;
    System.out.printf("%d\n", Math.pow(digit, 2));
    m /= 10;
}

Is this what you want?


Due to Andreas comment which said the order is reversed, I changed the code:

int length = number.length();
for (int i = length - 1; i >= 0; i--)
{
    int divisor = (int) Math.pow(10, i);
    int digit = n % divisor;
    System.out.printf("%d\n", Math.pow(digit, 2));
}

Also I could have written it as:

int length = number.length();
int divisor = (int) Math.pow(10, length - 1);
while (divisor > 0)
{
    int digit = n % divisor;
    System.out.printf("%d\n", Math.pow(digit, 2));
    divisor /= 10;
}

Upvotes: 1

Kodebetter
Kodebetter

Reputation: 47

If you want to print sq of individual digits.

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

Upvotes: 1

Andreas
Andreas

Reputation: 159135

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

Upvotes: 0

Hank D
Hank D

Reputation: 6481

Math.pow(j, 2) doesn't modify j, it returns a new value. You should capture the output of Math.pow to a variable and print that

Upvotes: 4

Related Questions