1002 写出这个数 (20 分)
读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字。
输入格式:
每个测试输入包含 1 个测试用例,即给出自然数 n 的值。这里保证 n 小于
10^100 。
输出格式:
在一行内输出 n 的各位数字之和的每一位,拼音数字间有 1 空格,但一行中最后一个拼音数字后没有空格。
输入样例:
1234567890987654321123456789 |
---|
输出样例:
yi san wu |
---|
做题思路
计算n的各项之和s,然后再用switch case将s的各项转换成pinyin,输出就好啦。
Notice:
- n的取值范围为 n <10^100 ,所以不用 int 而是用 BigInteger;
- 关于 0 和10,BigInteger有自己的表示方法,分别为BigInteger.ZERO 和BigInteger.TEN
- BigInteger有自己的 加减乘除取余 和int 的是不一样的;BigInteger:加法 add()函数;减法 subtract()函数;乘法 multipy()函数;除法 divide()函数;绝对值 abs()函数
- 将 BigInteger 转换成 int 为 int a = b.intValue();
代码展示
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String[] pinyin= new String[11];
Scanner input = new Scanner(System.in);
BigInteger n = input.nextBigInteger();//输入一个数n
BigInteger s = new BigInteger("0");
BigInteger p;
//特例,n=0的情况
if(n.compareTo(BigInteger.ZERO) == 0){
System.out.print("ling");
}
//
else {
while(n.compareTo(BigInteger.ZERO)!=0) {
p = n.remainder(BigInteger.TEN);
s = s.add(p);
n = n.divide(BigInteger.TEN);
}
int i = 0;
while(s.compareTo(BigInteger.ZERO)!=0) {
BigInteger qi = s.remainder(BigInteger.TEN);
s = s.divide(BigInteger.TEN);
int q = qi.intValue();//BigInteger转换为int
switch(q){
case 0 : pinyin[i] = "ling";break;
case 1 : pinyin[i] = "yi";break;
case 2 : pinyin[i] = "er";break;
case 3 : pinyin[i] = "san";break;
case 4 : pinyin[i] = "si";break;
case 5 : pinyin[i] = "wu";break;
case 6 : pinyin[i] = "liu";break;
case 7 : pinyin[i] = "qi";break;
case 8 : pinyin[i] = "ba";break;
case 9 : pinyin[i] = "jiu";break;
default:System.out.println("default");break;
}
i++;
}
int ii = i-1;
while(ii>0) {
System.out.print(pinyin[ii]+" ");
ii--;
}
System.out.print(pinyin[0]);
}
}
}
加油~