《算法竞赛·快冲300题》将于2024年出版,是《算法竞赛》的辅助练习册。
所有题目放在自建的OJ New Online Judge。
用C/C++、Java、Python三种语言给出代码,以中低档题为主,适合入门、进阶。
【题目描述】 数字1-n转换成英文单词,统计字母出现次数。
例如1-5,把写成英文单词分别是:one、two、three、four、five,累计19个字母。
数字342:three hundred and forty-two,包含23个字母
数字115:one hundred and fifteen,包含20个字母
单词“and”的使用方法遵循英语的规范,最终只需统计字母,不要统计空格和连字符。 。
【输入格式】 一个正整数n,n≤1000。
【输出格式】 输出一个数字表示答案。
【输入样例】
5
【输出样例】
19
这是一道难度不高的模拟题,需要细致地考虑各种情况,见代码中的注释。
【笔记】 提高编码能力 。
#include
using namespace std;
//one two three four five six seven eight nine ten
int a1[] = {0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3};
//eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty
int a2[] = {0, 6, 6, 8, 8, 7, 7, 9, 8, 8, 6};
//ten twenty thirty forty fifty sixty seventy eighty ninety hundred
int a3[] = {0, 3, 6, 6, 5, 5, 5, 7, 6, 6, 7};
int Count_100(int x){ //x小于100
if(x <= 10) return a1[x];
if(x <= 20) return a2[x - 10];
return a3[x / 10] + a1[x % 10];
}
int Count(int x){
if(x < 100) return Count_100(x);
if(x == 100) return 10; //one hundred
if(x == 1000) return 11; //one thousand
if(x % 100 == 0) return a1[x / 100] + 7;
return a1[x / 100] + 7 + 3 + Count_100(x % 100);
}
int main(){
int n, ans = 0;
cin >> n;
for(int i=1; i<=n; i++) ans += Count(i);
cout<<ans<<endl;
return 0;
}
import java.util.*;
public class Main {
//one two three four five six seven eight nine ten
static int[] a1 = {0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3};
//eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty
static int[] a2 = {0, 6, 6, 8, 8, 7, 7, 9, 8, 8, 6};
//ten twenty thirty forty fifty sixty seventy eighty ninety hundred
static int[] a3 = {0, 3, 6, 6, 5, 5, 5, 7, 6, 6, 7};
static int Count_100(int x) { //x小于100
if (x <= 10) return a1[x];
if (x <= 20) return a2[x - 10];
return a3[x / 10] + a1[x % 10];
}
static int Count(int x) {
if (x < 100) return Count_100(x);
if (x == 100) return 10; //one hundred
if (x == 1000) return 11; //one thousand
if (x % 100 == 0) return a1[x / 100] + 7;
return a1[x / 100] + 7 + 3 + Count_100(x % 100);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int ans = 0;
for (int i = 1; i <= n; i++) ans += Count(i);
System.out.println(ans);
}
}
# one two three four five six seven eight nine ten
a1 = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3]
# eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty
a2 = [0, 6, 6, 8, 8, 7, 7, 9, 8, 8, 6]
# ten twenty thirty forty fifty sixty seventy eighty ninety hundred
a3 = [0, 3, 6, 6, 5, 5, 5, 7, 6, 6, 7]
def count_100(x): # x小于100
if x <= 10: return a1[x]
if x <= 20: return a2[x - 10]
return a3[x // 10] + a1[x % 10]
def count(x):
if x < 100: return count_100(x)
if x == 100: return 10 # one hundred
if x == 1000: return 11 # one thousand
if x % 100 == 0: return a1[x // 100] + 7
return a1[x // 100] + 7 + 3 + count_100(x % 100)
n = int(input())
ans = 0
for i in range(1, n + 1): ans += count(i)
print(ans)