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

如何实现根据数字的字符串长度计算各位数字的幂次和?

Fixing Your Digit Power Sum Calculation in Java

Hey there! Let's get that logic un-stuck. Your goal is to calculate the sum of each digit in a number raised to the power of the total number of digits—like 1³ + 5³ + 3³ for 153, right? The issue with your current code is that the nested inner loop doesn't serve a clear purpose here, and you're missing key steps to convert characters to digits and compute the power.

Here's the corrected approach with explanations:

First, let's rewrite the code to work as intended, then break down each part:

int number = 153;
// Using String.valueOf() is a cleaner way to convert int to String than number+""
String originalNumber = String.valueOf(number);
int digitCount = originalNumber.length();
int totalSum = 0;

for (int i = 0; i < digitCount; i++) {
    // Convert the character digit to its integer value (e.g., '5' -> 5)
    int digit = originalNumber.charAt(i) - '0';
    
    // Option 1: Use Math.pow to calculate digit^digitCount
    totalSum += (int) Math.pow(digit, digitCount);
    
    // Option 2: If you prefer to calculate the power manually (no Math.pow)
    // int powerResult = 1;
    // for (int j = 0; j < digitCount; j++) {
    //     powerResult *= digit;
    // }
    // totalSum += powerResult;
}

System.out.println("Total sum: " + totalSum); // Outputs 153 for input 153

Key fixes and explanations:

  • No nested loop needed (unless you're calculating power manually): Your original inner loop was unnecessary because we can either use Math.pow() directly, or use a small inner loop only if we want to compute the power without relying on the Math class.
  • Convert character to integer: When you get a char from the String (like '1'), subtracting '0' converts it to the actual integer value (1) because of how ASCII values are structured.
  • Track the total sum: We initialize a totalSum variable to accumulate the result of each digit's power calculation as we iterate through the number's digits.

If you run this code with 153, it will correctly output 153—exactly the sum you're looking for.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:45:40