Java程序检查是否有Armstrong数
时间:2020-01-09 10:35:33 来源:igfitidea点击:
在这篇文章中,我们将看到一个Java程序来检查所传递的号码是否是Armstrong号码。如果数字等于我们将数字的每一位提高到该数字的位次幂并将其相加而得到的数字,则该数字就是阿姆斯特朗数字。
阿姆斯壮数字示例
371 = 33 + 73 + 13 = 27 + 343 +1 = 371
此处的位数是3,因此每个位数都会提高到3的幂并加。由于计算得出的数字等于原始数字,因此371是阿姆斯特朗数字。
1634 = 14 + 6 4 + 34 + 44 = 1 + 1296 + 81 + 256 = 1634
Java代码检查是否有阿姆斯特朗号
import java.util.Scanner; public class ArmstrongNumber { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter a number : "); int number = sc.nextInt(); System.out.println("Is " + number + " an Armstrong number- " + checkIfArmstrong(number)); sc.close(); } private static boolean checkIfArmstrong(int number){ // Converting to string and calculating length int numLength = (number+"").length(); int temp = number; int sum = 0; while(temp != 0 ){ int remainder = temp % 10; sum = sum + (int)Math.pow(remainder, numLength); temp = temp/10; } if(number == sum){ return true; }else{ return false; } } }
输出:
Please enter a number : 371 Is 371 an Armstrong number- true Please enter a number : 1634 Is 1634 an Armstrong number- true Please enter a number : 373 Is 373 an Armstrong number- false