前段时间参加了兴业银行信息科技部的面试,第一场是上机笔试,前面的题目不知道是啥,什么HP服务器架构,X86芯片等等,反正不懂,随便乱选,真不明白他们搞这样的笔试意义何在。最后两道是编程题,其中一个是数字转换,当时匆匆忙忙也没写好,今天闲下来了,随便写了些,并写了中英文转换两个版本。
思路是这样的,假如有1234567890这么一个数字,那么中文的形式是这样的:
1234567890=(12)億+(3456)万+(7890)
那么英文形式是这样的:
1234567890=(1)billion+(234)million+(567)thousand+(890)
有了这个以后,那剩下的就好说了,括号内部的中文形式的四位数字或者英文三位数字的转换就简单多了。
数字转中文:
public class NumberConvertToChinese {
public static String[] digits = {"壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
public static String[] bigs = {"", "万", "億"};
public static String numToString(int number) {
if (number == 0) {
return "零";
} else if (number < 0) {
return "负" + numToString(-1 * number);
}
int count = 0;
String str = "";
while (number > 0) {
if (number % 10000 != 0) {
str = numToString1000(number % 10000) + bigs[count] + str;
}
number /= 10000;
count++;
}
return str;
}
public static String numToString1000(int number) {
String str = "";
if (number >= 1000) {
str += digits[number / 1000 - 1] + "仟";
number %= 1000;
}
if (number >= 100) {
str += digits[number / 100 - 1] + "佰";
number %= 100;
}
if (number >= 10) {
str += digits[number / 10 - 1] + "拾";
number %= 10;
}
if (number >= 1 && number <= 9) {
str += digits[number - 1];
}
return str;
}
public static void main(String[] args) {
System.out.println(numToString(1234567890));
}
}
数字转英文:
public class NumberConvert {
public static String[] digits = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
public static String[] teens = {"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
public static String[] tens = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
public static String[] bigs = {"", "Thousands", "Million"};
public static String numToString(int number) {
if (number == 0) {
return "Zero";
} else if (number < 0) {
return "Negative " + numToString(-1 * number);
}
int count = 0;
String str = "";
while (number > 0) {
if (number % 1000 != 0) {
str = numToString100(number % 1000) + bigs[count] + " " + str;
}
number /= 1000;
count++;
}
return str;
}
public static String numToString100(int number) {
String str = "";
if (number >= 100) {
str += digits[number / 100 - 1] + " Hundred ";
number %= 100;
}
if (number >= 11 && number <= 19) {
return str + teens[number - 11] + " ";
} else if (number == 10 || number >= 20) {
str += tens[number / 10 - 1] + " ";
number %= 10;
}
if (number >= 1 && number <= 9) {
str += digits[number - 1] + " ";
}
return str;
}
public static void main(String[] args) {
System.out.println(numToString(123456789));
}
}
参考资料:
《Cracking the coding interview》