?如上规律,提供初始幂次,返回倍数,如1、2、51.
class DigPow
{
public:
static int digPow(int n, int p);
};
int DigPow::digPow(int n, int p) {
vector<int> my_array;
int temp = n;
int yushu;
while (n >= 10) {
yushu = n % 10;
n = n / 10;
my_array.push_back(yushu);
}
my_array.push_back(n);
int sum{ 0 };
int length = my_array.size();
for (int i = 0; i < length; i++) {
sum += pow( (my_array[i]) , (p + length - 1 - i));
}
//cout << sum % n << endl;
return sum % temp == 0 ? (sum / temp) : -1;
}
解法二:
#include <cmath>
class DigPow
{
public:
static int digPow(int n, int p)
{
uint64_t s = 0;
std::string nn = std::to_string(n);
for (auto e : nn)
s += pow((e - '0'), p++);
return !(s % n) ? s / n : -1;
}
};
|