1002 写出这个数 (20 point(s))
读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字。
输入格式:
每个测试输入包含 1 个测试用例,即给出自然数 n 的值。这里保证 n 小于 10100。
输出格式:
在一行内输出 n 的各位数字之和的每一位,拼音数字间有 1 空格,但一行中最后一个拼音数字后没有空格。
输入样例:
1234567890987654321123456789
输出样例:
yi san wu
代码:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String n = scanner.next(); char[] chars = n.toCharArray(); int sum = 0; for (char c : chars) { sum += c - '0'; } System.out.println(numToSpell(sum)); } private static String numToSpell(int sum) { int lastNum = 0; String spell = ""; StringBuilder sb = new StringBuilder(); do { lastNum = sum % 10; switch (lastNum) { case 0: spell = "ling"; break; case 1: spell = "yi"; break; case 2: spell = "er"; break; case 3: spell = "san"; break; case 4: spell = "si"; break; case 5: spell = "wu"; break; case 6: spell = "liu"; break; case 7: spell = "qi"; break; case 8: spell = "ba"; break; case 9: spell = "jiu"; break; } sum /= 10; if (sum != 0) { sb.insert(0, " " + spell); } else { sb.insert(0, spell); } } while (sum != 0); return sb.toString(); } }
注意点:
(1)由于输入的数字太长了,因此 Scanner() 不能使用 .nextInt() 形式,必须先以字符串形式 .next() 输入,然后再转化成数字。
(2)知识点1:char 类型的数字 - '0' 等于其对应的 int 类型的数字。例如:char 类型的 '1' 的 ASCII 码为 49,而 '0' 的 ASCII 码为 48,二者相减刚好为 1。
(3)知识点2:StringBuilder 往后添加字符串用的是 .append(),而往前添加字符串用的是 .insert(offset, str),添加在开头时,offset 置为 0 即可。