[LeetCode]273. Integer to English Words

Problem Description

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
[https://leetcode.com/problems/integer-to-english-words/]

思路

将数字按三位分出来,然后写一个将三位数转换成英文的方法,循环调用。
注意testcase!!!!

Code

package Q273;

public class Solution {

    public static String linkWords(String a, String b) {
        if (a.length() > 0 && b.length() > 0)
            return a + " " + b;
        else
            return a + b;
    }

    public static String linkWords(String a, String b, String c) {
        String tmp = "";

        if (a.length() > 0 && b.length() > 0)
            tmp = a + " " + b;
        else
            tmp = a + b;

        if (tmp.length() > 0 && c.length() > 0)
            return tmp + " " + c;
        else
            return tmp + c;
    }

    public static String getWords(int num) {
        String[] number = { "", "One", "Two", "Three", "Four", "Five", "Six",
                "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve",
                "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
                "Eighteen", "Nineteen" };
        String[] number2 = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty",
                "Sixty", "Seventy", "Eighty", "Ninety" };
        String ans = "";
        if (num / 100 > 0)
            ans = linkWords(ans, number[num / 100]) + " " + "Hundred";
        if (num % 100 < 20) {
            ans = linkWords(ans, number[num % 100]);
        } else {
            ans = linkWords(ans, number2[(num % 100) / 10]);
            ans = linkWords(ans, number[(num % 10)]);
        }
        return ans;
    }

    public static String numberToWords(int num) {
        if (num == 0)
            return "Zero";
        String ans = "";
        String[] number3 = { "", "Thousand", "Million", "Billion" };
        int tmp = num % 1000;
        int tmp2 = num / 1000;
        int i = 0;
        while (tmp2 > 0) {
            if(tmp!=0)  ans = linkWords(getWords(tmp), number3[i], ans);
            else ans=linkWords(getWords(tmp),ans);
            i++;
            tmp = (tmp2) % 1000;
            tmp2 = tmp2 / 1000;
        }
        if (tmp > 0){
            if (i > 0 && ans.equals(number3[i - 1]))
                ans = "";
            ans = linkWords(getWords(tmp), number3[i++], ans);

        }


        return ans;
    }

//  public static void main(String[] args) {
//      System.out.println(numberToWords(100000010));
//  }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值