我们认为一个数是 7 好数,当且仅当它的开头和结尾都是数字 7。给定一个正整数 n,请问在区间 [1, n] 中有多少个 7 好数。
数据范围很小,直接枚举一遍判断每个数的开头和结尾是否都是7即可
为了实现这一点,可以按照以下步骤进行:
#include <iostream>
#include <string>
using namespace std;
/**
* 计算 [1, n] 中的 7 好数的数量
* @param n 给定的正整数
* @return 7 好数的数量
*/
int count7GoodNumbers(int n) {
int count = 0; // 计数器
for(int i = 1; i <= n; ++i){
string s = to_string(i); // 将数字转换为字符串
if(s.front() == '7' && s.back() == '7'){ // 检查首位和末位是否为 '7'
count++;
}
}
return count;
}
int main(){
int n;
cin >> n; // 输入
cout << count7GoodNumbers(n) << endl; // 输出结果
return 0;
}
def count7GoodNumbers(n):
"""
计算 [1, n] 中的 7 好数的数量
:param n: 给定的正整数
:return: 7 好数的数量
"""
count = 0 # 计数器
for i in range(1, n + 1):
s = str(i) # 将数字转换为字符串
if s[0] == '7' and s[-1] == '7': # 检查首位和末位是否为 '7'
count += 1
return count
if __name__ == "__main__":
n = int(input()) # 输入
print(count7GoodNumbers(n)) # 输出结果
import java.util.Scanner;
public class Main {
/**
* 计算 [1, n] 中的 7 好数的数量
* @param n 给定的正整数
* @return 7 好数的数量
*/
public static int count7GoodNumbers(int n) {
int count = 0; // 计数器
for(int i = 1; i <= n; i++) {
String s = Integer.toString(i); // 将数字转换为字符串
if(s.charAt(0) == '7' && s.charAt(s.length() - 1) == '7'){ // 检查首位和末位是否为 '7'
count++;
}
}
return count;
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // 输入
System.out.println(count7GoodNumbers(n)); // 输出结果
}
}
我们认为一个数是 7 好数,当且仅当它的开头和结尾都是 7 。给定一个正整数 n ,请问 [1,n] 中有多少个 7 好数。
时间限制:1000ms
内存限制:262mb
函数的第一个参数输入一个整数 n(1<=n<=105)
输出答案
输入
100
输出
2
说明
区间 [1,100] 中只有 7 和 77 是 7 好数