1002. 写出这个数 (20)
读入一个自然数n,计算其各位数字之和,用汉语拼音写出和的每一位数字。
输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。这里保证n小于10100。
输出格式:在一行内输出n的各位数字之和的每一位,拼音数字间有1 空格,但一行中最后一个拼音数字后没有空格。
输入样例:
1234567890987654321123456789
输出样例:
yi san wu
#include<cstdio> #include<cstring> char change[][5] = { //二维数组,要用“” "ling","yi","er","san","si","wu","liu","qi","ba","jiu" }; int main(){ char str[110]; int ans[100]; gets(str); int len = strlen(str); int sum = 0,num = 0,i; for(i = 0; i < len; i++){ sum = sum + (str[i] - '0'); } while(sum != 0){ ans[num++] = sum % 10; sum /= 10; } for(i = num - 1; i >= 0; i--){ printf("%s",change[ans[i]]); if(i != 0) printf(" "); else printf("\n"); } return 0; }
python版
/* 参考C的步骤 */ week = ('ling','yi','er','san','si','wu','liu','qi','ba','jiu') num = input() len_num = len(num) sum = 0 for i in range(0,len_num): sum = sum + int(num[i]) list = [] while sum > 0: list.append(sum%10) sum = sum // 10 i = len(list) while i > 1: i = i-1 print(week[list[i]],end =' ') print(week[list[0]]) """ i = 0 while i < len_num: print(num[i]) i += 1 print("sum = %d"%sum) print(num) """
使用Python的内置函数操作
n = input() sum = 0 week = ('ling','yi','er','san','si','wu','liu','qi','ba','jiu') list2 = [] for i in range(len(n)): sum += int(n[i]) for j in range(len(str(sum))): list2.append(week[int(str(sum).split()[0][j])]) print(' '.join(list2))
其中
split()函数使用
split(str=””,num=string.count(str)) num=string.count(str)以str为分隔符截取字符串,如果num有指定值,则仅截取num+1个子字符串
str1 = input() for i in range(len(str1)): print(str1.split()[0][i])
join()函数
join(seq) 以指定字符为分隔符,将seq中所有的元素合并为一个新的字符串
str2 = input() print(' '.join(str2))