You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java将整数各位存入数组?求完善自幂数判断代码

Fixing Your Narcissistic Number Checker

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 originalNumber because we'll be altering number to 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 to int since Math.pow returns a double.
  • 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 calculates 3³ + 5³ + 1³ = 27 + 125 + 1 = 153, so it returns true.
  • Input 123: The sum is 1³ + 2³ + 3³ = 1 + 8 + 27 = 36, which doesn't match 123, so it returns false.

内容的提问来源于stack exchange,提问作者smdj92

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:16:53