zoukankan      html  css  js  c++  java
  • Leetcode 273.整数转换英文表示

    整数转换英文表示

    将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1

    示例 1:

    输入: 123

    输出: "One Hundred Twenty Three"

    示例 2:

    输入: 12345

    输出: "Twelve Thousand Three Hundred Forty Five"

    示例 3:

    输入: 1234567

    输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

    示例 4:

    输入: 1234567891

    输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

     1 class Solution {
     2     static String num1[]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
     3     static String num2[]={"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
     4     static String tens[]={"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
     5     public String numberToWords(int num) {
     6         if(num==0){
     7             return "Zero";
     8         }
     9         String result="";
    10         if(num>999999999){
    11             result+=numberToWordsWithThreeDIgit(num/1000000000)+" Billion";
    12             num%=1000000000;
    13         }
    14         if(num>999999){
    15             result+=numberToWordsWithThreeDIgit(num/1000000)+" Million";
    16             num%=1000000;
    17         }
    18         if(num>999){
    19             result+=numberToWordsWithThreeDIgit(num/1000)+" Thousand";
    20             num%=1000;
    21         }
    22         if(num>0){
    23             result+=numberToWordsWithThreeDIgit(num);
    24         }
    25         return result.trim();
    26     }
    27 
    28     public String numberToWordsWithThreeDIgit(int num){
    29         String result="";
    30         if(num>99){
    31             result+=" "+num1[num/100-1]+" Hundred";
    32         }
    33         num%=100;
    34         if(num>19){
    35             result+=" "+tens[num/10-2];
    36             num%=10;
    37         }else if(num>9){
    38             result+=" "+num2[num-10];
    39             num=0;
    40         }
    41         if(num>0){
    42             result+=" "+num1[num-1];
    43         }
    44         return result;
    45     }
    46 }


  • 相关阅读:
    [译]javascript中的条件语句
    [译]Javascript substring实例
    [译]Javasctipt中的substring
    [译]在Javascript中将string转化成numbers
    [译]Javascript基础
    [译]我们应该在HTML文档中何处放script标签
    [译]内联Javascript vs 外置Javascript
    [译]学习Javascript的工具
    MYSQL 重新设置自增值
    LINUX下的ssh登录之后的文件远程copy:scp命令(接前文ssh登录)
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10204954.html
Copyright © 2011-2022 走看看