Armstrong number what's wrong in this?

package Challenges;

import java.util.Scanner;

public class ArmstrongNumber {

public static void main(String[] args) 
{
	
	
	Scanner sc = new Scanner(System.in);
	
	int num = sc.nextInt();

	 int total = Armstrong(num);
	 
	 if(total==num)
	 {
		 System.out.println("true");
	 }
	 else
	 {
		 System.out.println("false");
	 }


}

public static int Armstrong(int num)
{
	int  temp, total = 0, count = 0;

	

	while (num > 0) {

		
		num = num/ 10;
		count++;
	}
	
	while (num > 0) {

		temp = num % 10;
		

		total = total + (int) Math.pow(temp, count);
		num =num/ 10;
		
	}

	return total;	

}
}

Hey @Nitya_Somani
logic is fine
Just a Mistake
After this steps num =0;
while (num > 0) {

	num = num/ 10;
	count++;

// ab num is 0
Therefore, store the value of the num in another variable.
correct code :
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int total = Armstrong(num);
if (total == num) {
System.out.println(“true”);
} else {
System.out.println(“false”);
}
}

public static int Armstrong(int num) {
	int temp, total = 0, count = 0;
	int p =num;
	while (p > 0) {
		p = p / 10;
		count++;
	}
	while (num > 0) {
		temp = num % 10;
		total = total + (int) Math.pow(temp, count);
		num = num / 10;
	}
	return total;
}

}

1 Like