华为机试-099-简单-HJ99.自守数
一、描述
自守数是指一个数的平方的尾数等于该数自身的自然数。例如:
25^2 = 625
76^2 = 5776
9376^2 = 87909376
请求出n(包括n)以内的自守数的个数
数据范围: 1 ≤ n ≤ 10000
1.1、输入描述
int型整数
1.2、输出描述
n以内自守数的数量。
二、示例
2.1、示例1
输入:
6
输出:
4
说明:
有0,1,5,6这四个自守数
2.2、示例2
输入:
1
输出:
2
说明:
有0, 1这两个自守数
三、答案(java)
3.1、方法一
主要使用String的endsWith() 方法,用于测试字符串是否以指定的后缀结束。如果参数表示的字符序列是此对象表示的字符序列的后缀,则返回 true;否则返回 false。注意,如果参数是空字符串,或者等于此 String 对象(用 equals(Object) 方法确定),则结果为 true。
package com.tzq.hwod;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
int count = 0;
for (int i = 0; i <= n; i++) {
String str = String.valueOf(i * i);
String s = String.valueOf(i);
if (str.endsWith(s)) {
count++;
}
}
System.out.println(count);
}
}
}
四、答案(python 3)
4.1、方法一
#!/usr/bin/python
# -*- coding: UTF-8 -*-
while True:
try:
n = int(input())
count = 0
for i in range(n+1):
if str(i) == str(i**2)[-len(str(i)):]:
count += 1
print(count)
except:
break