輸入:|輸出:
5 - > 12(1^2 + 2^2 = 5)
500 - > 18888999(1^2 + 8^2 + 8^2 + 8^2 + 9^2 + 9^2 + 9^2 = 500)
我寫了一個非常簡單的蠻力解決方案,但是它有很大的性能問題:
#include <iostream>
using namespace std;
int main() {
int n;
bool found = true;
unsigned long int sum = 0;
cin >> n;
int i = 0;
while (found) {
++i;
if (n == 0) { //The code below doesn't work if n = 0, so we assign value to sum right away (in case n = 0)
sum = 0;
break;
}
int j = i;
while (j != 0) { //After each iteration, j's last digit gets stripped away (j /= 10), so we want to stop right when j becomes 0
sum += (j % 10) * (j % 10); //After each iteration, sum gets increased by *(last digit of j)^2*. (j % 10) gets the last digit of j
j /= 10;
}
if (sum == n) { //If we meet our problem's requirements, so that sum of j's each digit squared is equal to the given number n, loop breaks and we get our result
break;
}
sum = 0; //Otherwise, sum gets nullified and the loops starts over
}
cout << i;
return 0;
}
我要找快速解決方案 問題。
你的問題不是很好。例如,你可以說'任何數字 - > 1111111 ... 1111'。這將是一個微不足道卻又正確的解決方案。我認爲你必須回到制定階段。 –
問題狀態爲「找到數字的平方和加上給定數字的**最小**整數」 –
我的不好,你是對的!這個問題比它看起來更有趣,可能應該更好。我會建議在問題的主體中完整地說明問題,而不是依賴問題標題。 –