PAT甲级练习1005. Spell It Right (20)

    xiaoxiao2021-03-26  32

    1005. Spell It Right (20)

    时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue

    Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.

    Input Specification:

    Each input file contains one test case. Each case occupies one line which contains an N (<= 10100).

    Output Specification:

    For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.

    Sample Input: 12345 Sample Output: one five Java里有处理大数的工具类 BigInteger 和 BigDecimal 可供使用,方便不少。

    import java.math.BigInteger; import java.util.Scanner; public class Main { public static void main(String[] args) { String[] number = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; BigInteger sum = BigInteger.ZERO; StringBuffer sum_string; int sum_int; Scanner s = new Scanner(System.in); BigInteger n = s.nextBigInteger(); while(n != BigInteger.valueOf(0)){ sum = sum.add(n.mod(BigInteger.TEN)); n = n.divide(BigInteger.valueOf(10)); } sum_string = new StringBuffer(sum.toString()); sum_string.reverse(); sum_int = Integer.valueOf(sum_string.toString()); System.out.printf("%s", number[sum_int]); sum_int = sum_int/10; for(int i=1; i<sum_string.length(); i++){ System.out.printf(" %s", number[sum_int]); sum_int = sum_int/10; } } } 但是看了一下别人的代码,发现!!!

    可以直接字符串读入,然后直接把各位字符想加直接处理得到!!!

    还是应该聪明一点

    按该思路的代码如下

    import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); String[] number = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; String sum_string; int sum_int = 0; Scanner s = new Scanner(System.in); sum_string = s.next(); for(int i=0; i<sum_string.length(); i++){ sum_int += sum_string.charAt(i) - '0'; } while(sum_int/10 != 0){ list.add(sum_int); sum_int /= 10; } System.out.printf("%s", number[sum_int]); for(int i=list.size();i>0;i--){ System.out.printf(" %s", number[list.get(i-1)]); } } }

    转载请注明原文地址: https://ju.6miu.com/read-661920.html

    最新回复(0)