PAT练习题(甲级) 1005 Spell It Right (20分)(Java实现)

PAT 1005 Spell It Right (20分)

题目

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里int类型按位求和比较困难,所以直接用String类型
  • 然后就能输出了

代码实现

import java.util.Scanner;

/**
 * @BelongsProject: Pattest
 * @Author: Huqifu
 * @CreateTime: 2020-05-08-14-45
 * @Descirption: Pat1005
 */
 
public class Testfive {
    static String[] number = {"zero","one","two","three","four","five","six","seven","eight","nine"};
    //给定数组进行配对
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        int sum = 0;
        
        //使用for循环进行求和
        for(int i=0; i<str.length(); i++) {
            sum += str.charAt(i) - '0';
        }
        
        //输出
        str = String.valueOf(sum);
        for(int i=0; i<str.length(); i++) {
            if(i == 0) System.out.print(number[str.charAt(i) - '0']);
            else System.out.print(" " + number[str.charAt(i) - '0']);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45062103/article/details/105998292