- cpp/stl/string
题目链接:自守数_牛客题霸_牛客网 (nowcoder.com)
题目描述:
自守数是指一个数的平方的尾数等于该数自身的自然数。例如:25^2 = 625,76^2 = 5776,9376^2 = 87909376。请求出n(包括n)以内的自守数的个数
示例1:
输入:6
输出:4
说明:有0,1,5,6这四个自守数
输入:1
输出:2
说明:有0,1这两个自守数
💡
📖流程描述:、
- 定义个数n,自守数个数count=1 (0不进入while循环,初始值为1);
- 从后遍历n,是自守数,则count+1;
- 1 判断自守数,用to_string将n和平方转为字符串;
- 2 计算两字符串差sz,用迭代器区间构造后段tmp;
- 3 比较两字符串是否相同;
⌨️代码实现:
#include <iostream>
#include <string>
using namespace std;
//2. 判断自守数
bool is_self(int x)
{
//2.1 转为字符串
string num(to_string(x));
string mul(to_string(x*x));
int sz = mul.size() - num.size();
//2.2 迭代器区间构造
string tmp(mul.begin() + sz, mul.end());
return tmp == num;
}
int main()
{
int n = 0, count = 1; //0是自守数
cin >> n;
//1. 从后遍历n,是自守数,则count+1;
while (n) if (is_self(n--)) ++count;
cout << count;
return 0;
}
运行结果:
