📜  给定幂的给定数字的数字总和

📅  最后修改于: 2021-05-07 08:38:31             🧑  作者: Mango

给定一个数字,我们需要找到将数字提高到指定幂后得到的数字的所有数字的总和。
例子:

Input: number = 5, power = 4 
Output: 13
Explanation:
Raising 5 to the power 4 we get 625.
Now adding all the digits = 6 + 2 + 5


Input: number = 9, power = 5
Output: 27
Explanation:
Raising 9 to the power 5 we get 59049.
Now adding all the digits = 5 + 9 + 0 + 4 + 9

解释了Python的方法。我们使用了pow()函数来计算幂值的底数。然后,我们使用str()方法提取了每个数字作为字符串。由于我们无法计算字符串的总和,因此我们使用int()方法将每个字符串数字转换回整数。最后,我们使用sum()函数来获取所有数字的总和。该解决方案在Python看起来非常简单,但在其他语言中不会那么短。在运行完这两个代码之后,可以比较经过的时间和给定语言(即Python和Java)使用的内存。
下面是上述想法的实现:

C++
// CPP program to illustrate the given problem
#include
using namespace std;
 
int calculate(int n, int power)
{
    int sum = 0;
    int bp = (int)pow(n, power);
    while (bp != 0) {
        int d = bp % 10;
        sum += d;
        bp /= 10;
    }
    return sum;
}
 
// Driver Code
int main()
{
    int n = 5;
    int power = 4;
    cout << calculate(n, power);
}
 
// This code is contributed by Nikita Tiwari


Java
// Java program to illustrate the given problem
public class base_power {
    static int calculate(int n, int power)
    {
        int sum = 0;
        int bp = (int)Math.pow(n, power);
        while (bp != 0) {
            int d = bp % 10;
            sum += d;
            bp /= 10;
        }
        return sum;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 5;
        int power = 4;
        System.out.println(calculate(n, power));
    }
}


Python3
# Python program to illustrate the given problem
def calculate(n, power):
    return sum([int(i) for i in str(pow(n, power))])
     
# Driver Code
n = 5
power = 4
print (calculate(n, power))


C#
// C# program to find sum of digits of
// a given number to a given power
using System;
 
public class base_power
{
     
    // Function to calculate sum
    static int calculate(int n, int power)
    {
        int sum = 0;
        int bp = (int)Math.Pow(n, power);
        while (bp != 0)
        {
            int d = bp % 10;
            sum += d;
            bp /= 10;
        }
        return sum;
    }
 
    // Driver Code
    public static void Main()
    {
        int n = 5;
        int power = 4;
        Console.WriteLine(calculate(n, power));
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:

13