题解 | #自守数#

自守数

https://www.nowcoder.com/practice/88ddd31618f04514ae3a689e83f3ab8e

使用尾部字符遍历判断是否相等来获得自守数。
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

bool Isrepe(int k) {
    int k2k = pow(k, 2);
    string s1 = to_string(k);
    string s2 = to_string(k2k);

    int n1 = s1.size() - 1, n2 = s2.size() - 1;
    while (n1 >= 0) {
        if (s1[n1] != s2[n2]) {
            break;
        }
        n1--;
        n2--;
    }
    if (n1 < 0) return true;
    else return  false;
}

int main() {
    int n;
    while (cin >> n) {
        int ans = 0;
        for (int i = 0; i <= n; i++) {
            if (Isrepe(i)) ans++;
        }
        cout << ans << endl;
    }
    return 0;
}


#华为机试#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务