Reputation: 49
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
Upvotes: 2
Views: 259
Reputation: 14082
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 aString
[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.
Upvotes: 0
Reputation: 4191
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
Upvotes: 1
Reputation: 56443
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)
.
Upvotes: 2