如何用Java将整数各位存入数组?求完善自幂数判断代码
Hey there! Let's get your self-power number (自幂数) checker working properly. Right now, your code only grabs the last digit of the input—let's fix that and build out the full logic step by step.
Step 1: Extract All Digits
To get every digit from the number, we can use a loop that repeatedly captures the last digit (with %10) and then removes that digit from the number (with integer division /10). We'll also need to save the original number since we'll be modifying the input value during the loop.
Step 2: Calculate the Sum of Digits Raised to the Digit Count
A narcissistic number equals the sum of its own digits each raised to the power of how many digits it has. So first we'll count the digits, then compute each digit's power and add them up, finally comparing the sum to the original number.
Modified Full Code
import java.util.Scanner; public class narc { public static void main(String[] args){ Scanner myScan = new Scanner(System.in); System.out.println("enter number: "); int digit = myScan.nextInt(); System.out.println(narcNumber(digit)); myScan.close(); // Clean up the scanner resource! } public static boolean narcNumber(int number) { // Negative numbers can't be narcissistic numbers if (number < 0) { return false; } int originalNumber = number; int digitCount = Integer.toString(originalNumber).length(); int sum = 0; // Loop to extract each digit and calculate its power while (number > 0) { int lastDigit = number % 10; // Calculate the digit raised to the power of digit count, cast to int since we're dealing with integers sum += (int) Math.pow(lastDigit, digitCount); number = number / 10; // Remove the last digit from the number } // Special case: 0 is a narcissistic number (0^1 = 0) if (originalNumber == 0) { return true; } // Check if the sum matches the original number return sum == originalNumber; } }
Key Details Explained
- Preserve the Original Number: We store the input in
originalNumberbecause we'll be alteringnumberto strip digits during the loop. - Count Digits Easily:
Integer.toString(originalNumber).length()is a simple way to get the digit count. If you prefer not to use string conversion, you could also count digits with a separate loop. - Power Calculation:
Math.pow(lastDigit, digitCount)handles raising each digit to the correct power. We cast the result tointsinceMath.powreturns adouble. - Loop Through Digits: The
while (number > 0)loop runs until all digits are processed—each iteration grabs the last digit, adds its power to the sum, then removes the digit. - Edge Cases: We explicitly handle
0(a valid narcissistic number) and negative numbers (which don't qualify).
Test It Out
- Input
153: The code calculates3³ + 5³ + 1³ = 27 + 125 + 1 = 153, so it returnstrue. - Input
123: The sum is1³ + 2³ + 3³ = 1 + 8 + 27 = 36, which doesn't match 123, so it returnsfalse.
内容的提问来源于stack exchange,提问作者smdj92

