题解 | 自守数
自守数
https://www.nowcoder.com/practice/88ddd31618f04514ae3a689e83f3ab8e?tpId=37&tqId=21322&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D2%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
转换成字符串去比较
#include <iostream>
using namespace std;
bool is_automorph(int n) {
if(n == 0) return true;
long square = n * n;
string s1 = to_string(n);
string s2 = to_string(square);
int idx1 = s1.size() - 1, idx2 = s2.size() - 1;
while(idx1 >= 0) {
if(s1[idx1--] != s2[idx2--]) return false;
}
return true;
}
int main() {
int count = 0;
int n;
cin >> n;
for(int i = 0; i <= n; ++i) {
if(is_automorph(i)) ++count;
}
cout << count << endl;
return 0;
}
查看8道真题和解析