27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 19 | Moderate<br />

19.6 Given an integer between 0 <strong>and</strong> 999,999, print an English phrase that describes <strong>the</strong><br />

integer (eg, “One Thous<strong>and</strong>, Two Hundred <strong>and</strong> Thirty Four”).<br />

SOLUTION<br />

pg 89<br />

This is not an especially challenging problem, but it is a long <strong>and</strong> tedious one. Your interviewer<br />

is unlikely to ask to see every detail, but he / she will be interested in how you approach<br />

<strong>the</strong> problem.<br />

1 public static String numtostring(int num) {<br />

2 StringBuilder sb = new StringBuilder();<br />

3<br />

4 // Count number of digits in num.<br />

5 int len = 1;<br />

6 while (Math.pow((double)10, (double)len ) < num) {<br />

7 len++;<br />

8 }<br />

9<br />

10 String[] wordarr1 = {“”,”One ”, “Two ”, “Three ”, “Four ”,<br />

11 “Five ”, “Six ”, “Seven ”, “Eight ”,”Nine ”};<br />

12 String[] wordarr11 = {“”, “Eleven ”, “Twelve ”, “Thirteen ”,<br />

13 “Fourteen ”, “Fifteen ”, “Sixteen ”,<br />

14 “Seventeen ”, “Eighteen ”, “Nineteen ”};<br />

15 String[] wordarr10 = {“”,”Ten ”, “Twenty ”, “Thirty ”, “Forty ”,<br />

16 “Fifty ”, “Sixty ”, “Seventy ”, “Eighty ”,<br />

17 “Ninety “};<br />

18 String[] wordarr100 = {“”, “Hundred ”, “Thous<strong>and</strong> ”};<br />

19 int tmp;<br />

20 if (num == 0) {<br />

21 sb.append(“Zero”);<br />

22 } else {<br />

23 if (len > 3 && len % 2 == 0) {<br />

24 len++;<br />

25 }<br />

26 do {<br />

27 // Number greater than 999<br />

28 if (len > 3) {<br />

29 tmp = (num / (int)Math.pow((double)10,(double)len-2));<br />

30 // If tmp is 2 digit number <strong>and</strong> not a multiple of 10<br />

31 if (tmp / 10 == 1 && tmp%10 != 0) {<br />

32 sb.append(wordarr11[tmp % 10]) ;<br />

33 } else {<br />

34 sb.append(wordarr10[tmp / 10]);<br />

35 sb.append(wordarr1[tmp % 10]);<br />

36 }<br />

2 7 1<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Additional Review Problems

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!