当前位置:   article > 正文

Java | Leetcode Java题解之第273题整数转换英文表示

Java | Leetcode Java题解之第273题整数转换英文表示

题目:

题解:

  1. class Solution {
  2. String[] singles = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
  3. String[] teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
  4. String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
  5. String[] thousands = {"", "Thousand", "Million", "Billion"};
  6. public String numberToWords(int num) {
  7. if (num == 0) {
  8. return "Zero";
  9. }
  10. StringBuffer sb = new StringBuffer();
  11. for (int i = 3, unit = 1000000000; i >= 0; i--, unit /= 1000) {
  12. int curNum = num / unit;
  13. if (curNum != 0) {
  14. num -= curNum * unit;
  15. sb.append(toEnglish(curNum)).append(thousands[i]).append(" ");
  16. }
  17. }
  18. return sb.toString().trim();
  19. }
  20. public String toEnglish(int num) {
  21. StringBuffer curr = new StringBuffer();
  22. int hundred = num / 100;
  23. num %= 100;
  24. if (hundred != 0) {
  25. curr.append(singles[hundred]).append(" Hundred ");
  26. }
  27. int ten = num / 10;
  28. if (ten >= 2) {
  29. curr.append(tens[ten]).append(" ");
  30. num %= 10;
  31. }
  32. if (num > 0 && num < 10) {
  33. curr.append(singles[num]).append(" ");
  34. } else if (num >= 10) {
  35. curr.append(teens[num - 10]).append(" ");
  36. }
  37. return curr.toString();
  38. }
  39. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/868937
推荐阅读
相关标签
  

闽ICP备14008679号