Cracking Coding Interview - 16.8 English Int

English Int: Given any integer, print an English phrase that describes the integer (e.g., “One Thou­sand, Two Hundred Thirty Four”).

Hints: #502, #588, #688

解法

英文对于数字的单词是:

1
2
3
4
5
6
1: one, two, three, four, five, six, seven, eight, nine
10: ten, twenty, thirty, fourty, fifty, sixty, seventy, eighty, ninety
100: one hundred, two hundred, three hundred, ...
1,000: one thousand, two thousand, three thousand, ...
1,000,000: one million, two million, three million, ...
1,000,000,000: one billion, two billion, three billion, ...

其中对于11~19是这样的:

1
2
11      12      13        14        15       16       17         18        19
eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen

对于10、20、30是这样的:

1
2
10   20      30      40      50     60     70       80      90
ten, twenty, thirty, fourty, fifty, sixty, seventy, eighty, ninety

在1000以下,是10倍进位,在1000以上则是1000倍进位。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
private static final int BILLION = 1000000000;
private static final int MILLION = 1000000;
private static final int THOUSAND = 1000;
private static final int HUNDRED = 100;
private static final int TEN = 10;


private static final String[] TENS = new String {"Twenty", "Thirty", ...};
private static final String[] TEENS = new String {"Ten", "Eleven", ...};
private static final String[] ONES = new String {"One", "Two", ...}

public String toEnglish(int n) {
  String result = "";
  if (n < 0) {
    result += "Negative ";
    n = -n;
  }
  if (n >= BILLION) {
    int c = n / BILLION;
    result += toEnglish(c) + " Billion ";
    n = n % BILLION;
  }
  
  if (n >= MILLION) {
    int c = n / MILLION;
    result += toEnglish(c) + " Million ";
    n = n % MILLION;
  }
  
  if (n >= THOUSAND) {
    int c = n / THOUSAND;
    result += toEnglish(c) + " Thousand ";
    n = n % THOUSAND;
  }
  
  if (n >= HUNDRED) {
    int c = n / HUNDRED;
    result += toEnglishOne(c) + " Hundred ";
    n = n % HUNDRED;
  }
  
  if (n >= TEN) {
    int c = n / TEN;
    if (c > 1) {
      result += toEnglishTen(c);
      n = n % 10;
    } else if (c == 1) {
      result += toEnglishTeen(n);
      return result;
    }
  }
  
  if (n > 0) {
    result += toEnglishOne(n);
  }
  
  return result;
}

public String toEnglishTen(int n) {
  return TENS[n - 2];
}

public String toEnglishTeen(int n) {
  return TEENS[n - 10];
}

public String toEnglishOne(int n) {
  return ONES[n - 1];
}

版权

评论