zoukankan      html  css  js  c++  java
  • LeetCode-Integer to English Words

    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"

    Solution:

    BE CAREFUL: all kinds of corner cases

    public class Solution {
        String[] suffixs = new String[]{"","Thousand", "Million","Billion"};
        String[] tens = new String[]{"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty", "Ninety"};
        String[] tenTwenty = new String[]{"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
        String[] singles = new String[]{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
        
        public String numberToWords(int num) {
            if (num==0) return "Zero";
            
            StringBuilder builder = new StringBuilder();
            int base = 1000;
            int index = 0;
            while (num!=0){
                int sectionNum = num%base;
                num = num / base;
                addSection(builder,sectionNum,suffixs[index++]);
            }
            return builder.toString().trim();
        }
        
        public void addSection(StringBuilder builder, int sectionNum, String suffix){
            if (sectionNum==0){
                return;
            }
            
            builder.insert(0," "+suffix);
            
            int hundreds = sectionNum / 100;
            int left = sectionNum % 100;
            
            if (left > 0){
                if (left<10){
                    builder.insert(0,singles[left]).insert(0," ");
                } else if (left>=10 && left < 20){
                    builder.insert(0,tenTwenty[left-10]).insert(0," ");
                } else {
                    String temp = " " + tens[left/10] + ((left%10==0) ? "" : (" " + singles[left%10]));
                    builder.insert(0,temp);
                }
            }
            
            if (hundreds>0){
                String temp = " " + singles[hundreds] + " Hundred";
                builder.insert(0,temp);
            }
        }
    }
  • 相关阅读:
    QTP 处理webtable中的数据
    Error 1406.Setup cannot write the value Microsoft
    QTP打开WinTree中的指定节点
    Excel数据操作
    VBS中实现函数多返回值
    QTP的回放模式
    VBS中运行应用程序的两种方式及WshShell对像浅析
    程序员奇葩面试的奇葩问题
    Android如何实现毛玻璃效果之Android高级模糊技术
    Android通过用代码画虚线椭圆边框背景来学习一下shape的用法
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5858592.html
Copyright © 2011-2022 走看看