小编准备考PAT甲级的证,因此开始刷题中。将刷过的题及自己所编的代码进行整理分享。
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.
输入描述:
Each input file contains one test case. Each case occupies one line which contains an N (<= 10100).
输出描述:
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.
示例1
输入
12345
输出
one five
代码:
package Match;
import java.util.Scanner;
/**
* Spell It Right (20)
* @version 1.0
* @author Liu
*/
public class Match1005 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
char[] stringArray = string.toCharArray();
int sum = 0;
for (int i = 0; i < stringArray.length; i++) {
sum += stringArray[i] - 48;
}
int ge = sum % 10;
int shi = sum / 10 % 10;
int bai = sum / 100;
String result = null;
if (bai == 0) {
if (shi==0) {
result = getEng(ge);
} else {
result = getEng(shi);
result += " " + getEng(ge);
}
} else {
result = getEng(bai);
result += " " +getEng(shi);
result += " " + getEng(ge);
}
System.out.print(result);
}
public static String getEng(int num) {
String engString = null;
switch (num) {
case 0:
engString = "zero";
break;
case 1:
engString = "one";
break;
case 2:
engString = "two";
break;
case 3:
engString = "three";
break;
case 4:
engString = "four";
break;
case 5:
engString = "five";
break;
case 6:
engString = "six";
break;
case 7:
engString = "seven";
break;
case 8:
engString = "eight";
break;
case 9:
engString = "nine";
break;
default:
break;
}
return engString;
}
}
解题思路:
首先,根据大概的计算可以得出10的100次方的每一位相加的和不大于1000,最多为三位数字。
根据scanner.nextLine()读取到数字,将其转为字符型数组,
int sum = 0;
for (int i = 0; i < stringArray.length; i++) {
sum += stringArray[i] - 48;
}
该部分是计算个位数字的和,其中48是根据‘1’-1(字符1减去数字1)得出来的差。ge为各位数字,shi为十位数字,bai为百位数字。然后判断和是否为三位数字,即bai是否为0,若不为0,则将每一位相对应的英文进行拼接即可。若bai为0,需要判断shi是否为0,不为0,直接进行拼接即可,若为0,则结果即为个位数字相对应的英文。