【LeetCode】Integer to English Words

来源:互联网 发布:哈萨克歌曲软件baigie 编辑:程序博客网 时间:2024/05/16 18:19

题目: 

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231- 1.

For example,

123 -> "One Hundred Twenty Three"12345 -> "Twelve Thousand Three Hundred Forty Five"1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

思路:


题木整体思路比较简单,只需把整个数字化为 3 个数字一组, 进行处理。同时, 把英文单词分为不同的等级存放在数组里,需要的时候方便调用
 

要注意的是化为英文,单词之间的空格。话不多说代码入下:


public class Solution {    public String numberToWords(int num) {        String[] units = {""," Thousand"," Million"," Billion"};         String[] ten = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};          String[] hundred = {"","Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};          //initialize the arrays                String rst = "";        int count= 0;// keep track of the unit        while(num != 0){            int curDigit = num % 1000;//get the last three digits            String curName = "";            if (curDigit > 99){//get the hundred digit                curName = ten[(curDigit / 100)] + " Hundred";                curDigit = curDigit % 100;            }            if (curDigit < 20 && curDigit > 0) {                if (curName.length() >0)// add an empty space if necessary                    curName = curName +" ";                curName = curName + ten[curDigit];            }            else if(curDigit >= 20){                if (curName.length() >0)                    curName = curName +" ";                String tmpTen = hundred[curDigit / 10];                      String tmpOne = curDigit % 10 == 0? "" : (ten[curDigit % 10]);                                String tmp = "";                if(tmpTen.length() > 0 && tmpOne.length() > 0)                    tmp = tmpTen + " "+ tmpOne;                else                     tmp = tmpTen+tmpOne;                curName = curName + tmp;            }           if (curName.length() >0)                    curName = curName + units[count];                        count ++;                        if(rst.length()>0 && curName.length() > 0)                curName = curName + " ";            rst = curName + rst;            num = num / 1000;        }        return rst.length() > 0 ?rst: "Zero";            }}



原创粉丝点击