今天开始对自己的跳槽过程做个记录吧。主要是因为在上课的过程中有人提到最好自己写技术博客,这样方便自己回顾和复习,同时可以尝试把思路讲清楚。
已经刷了一段时间的题了,主要针对的是Facebook的面试题。现在想想,当时接了Facebook的offer是不是就不用再刷了。。。诶但也没办法假设。。。人生经历就是各种各样的机缘巧合。。。
针对安卓方面的学习/复习,会单开一篇。这篇主要把自己做题学习和实践的做法思路写出来。
273. Integer to English Words:https://leetcode.com/problems/integer-to-english-words/
算法思路:
-
使用三个String array处理20以下数字,10、20、30...90的数字和千位数:
private String[] UNDER_TWENTY = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; private String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; private String[] THOUSANDS = {"", "Thousand", "Million", "Billion", "Trillion"};
-
创建helper function处理千位以内的数字
-
调用helper function加入千位array里面的单位("", "Thousand", "Million", "Billion", "Trillion");
注意事项:
-
helper function里面,hardcode “hundred”的String;
-
学会自调用helper()小于20的情况来处理大于20的数字(20-99,100-999);
-
helper function后面注意加空格“ ”;
-
注意在调用helper()的时候,check "num%1000 != 0",这样可以避免1,000,000这样的数字还有Thousand加在里面;
最终代码:
class Solution {
private String[] UNDER_TWENTY = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private String[] THOUSANDS = {"", "Thousand", "Million", "Billion", "Trillion"};
public String numberToWords(int num) {
if(num == 0) {
return "Zero";
}
// handle Thousands with helper;
String res = "";
int index = 0;
// 234, 212, 345, 678
while(num != 0) {
if(num % 1000 != 0) {
String currentVal = res.toString();
res = helper(num%1000) + THOUSANDS[index] + " " + res;
}
num /= 1000;
index++;
}
return res.trim();
}
// handle numbers smaller than 1000;
private String helper(int num) {
if(num == 0) {
return "";
} else if (num < 20) {
return UNDER_TWENTY[num] + " ";
} else if (num < 100) {// 20 -> 99: e.g. 84 -> TENS[num/10] + " " + UNDER_TWENTY[num%10];
// 30 ->
return TENS[num/10] + " " + helper(num%10);
} else { // //100 -> 999 -> 365 -> UNDER_TWENTRY[num/100] + " Hundred " + helper(num%100);
return UNDER_TWENTY[num/100] + " Hundred " + helper(num%100);
}
}
}