LeetCode 273. Integer to English Words

We divide the number every 4 digits,

for each interval, it's  xxx hundreds + ( xxxty + number < 10) or (number < 20) +  Thousands/millions/billions/""

we get the number in each interval by %1000. if %1000 == 0 then we skip this loop.

if input == 0 just return "zero" (because we don't have other place to use zero.)

Code:

class Solution {

    private final String[] SPECIALS = {"","One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};

    private final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty","Seventy", "Eighty", "Ninety"};

    private final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};


    public String result = "";

    public String numberToWords(int num) {

        int bit = 0;

        if(num == 0) return "Zero";

        while(num != 0){

            int value = num % 1000;

            if(value != 0){

            result = helper(value) +" "+ THOUSANDS[bit] + " "+ result.trim();

            }

            num = num/1000; 

            bit++;

        }

        return result.trim();

    }


    public String helper(int num) {

        String s = "";

        int hundred = num / 100;

        if(hundred != 0){

            s = SPECIALS[hundred] + " Hundred ";

            num = num % 100;

        }

        if(num < 20){

            s =  s + SPECIALS[num];

        }else{

            s = s + TENS[num/10] +" "+ SPECIALS[num%10];

        }

        return s.trim();

    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。