简体   繁体   中英

check if a number is an Armstrong number java

 public static void main(String[] args) {
    System.out.print("Please enter a number:"+" ");
    Scanner scan= new Scanner(System.in);
    long number=scan.nextLong();
    String num=String.valueOf(number);   // simple way to get the number of digits in a number
    long sum=0;
    for(int i=0;i<num.length();i++)
    {

        sum+=Math.pow(num.charAt(i), num.length());

    }

    if(sum==number)
    {
        System.out.print(number+" "+"is an armstrong number");
    }
    else
    {
        System.out.print(number+" "+"is not an armstrong number");
    }
}

i need to know what is wrong with this code, the sum line is not working properly. for example if i enter the number 371 (Armstrong number) the output of the sum suppose to be 371 but the output that appears according to my code is 416675371

Currently, you're applying the Math#pow on the ASCII code of the character returned from num.charAt(i) rather than the digit itself. To retrieve the digit itself rather than the ASCII representation then use Character.getNumericValue(num.charAt(i)) instead of num.charAt(i) .

Another way to do this is just find the difference between the char and the ascii value of '0':

for(int i=0;i<num.length();i++)
{
    sum += Math.pow(num.charAt(i) - '0', num.length());
}

Note : The ascii value of '0' (the digit) is 48

You can do something like this:

sum += Math.pow(Integer.parseInt(String.valueOf(num.charAt(i))), num.length());

How It Works :

Suppose you have the number 371 which consists of 3 digits, so when you get the String value num by invoking this method String.valueOf(number); on the number inputted, the String num will have a length of 3 .

Now in the for loop , in every round, it will calculate the power of each digit after reading it as a char at every index specified by i [ num.charAt(i) ], then reading it as a String [ String.valueOf() ], finally parsing it as an Integer [ Integer.parseInt() ].

At the end of every loop, the calculation will be added to the sum variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM