lintcode 9 Fizz Buzz
阿新 • • 發佈:2018-11-09
題目描述
Description
Given number n. Print number from 1 to n. But:
-
when number is divided by 3, print “fizz”.
-
when number is divided by 5, print “buzz”.
-
when number is divided by both 3 and 5, print “fizz buzz”.
Example
If n = 15, you should return:[
“1”, “2”, “fizz”,
“4”, “buzz”, “fizz”,
“7”, “8”, “fizz”,
“buzz”, “11”, “fizz”,
“13”, “14”, “fizz buzz”
]
Challenge
Can you do it with only one if statement?
被3整除就fizz,被5整除就buzz,被3和5整除就fizz buzz
題目很簡單,挑戰很有意思,所以就記錄一下。挑戰讓我們只用一個if來寫
思路
這道題呢,當然如果用三元運算子一直巢狀也是可以的,不過明顯不是這道題的意思
剛開始不知道怎麼使用一個if來完美的解決這道題,後來看到一個老哥的解法,覺得還是比較有意思的
是這樣的,寫一個函式helper用來判斷整除,然後用字串拼接來輸出字串:
- 如果被3整除,字串加上“fizz”
- 如果被15整除,加上“ ”
- 如果被5整除,加上“buzz”
String w = helper(i, 3, "fizz") + helper(i, 15, " ")
+ helper(i, 5, "buzz");
程式碼
public List<String> fizzBuzz(int n) {
List<String> strings = new LinkedList<>();
for (int i = 1; i <= n; i++) {
String w = helper(i, 3, "fizz" ) + helper(i, 15, " ") + helper(i, 5, "buzz");
if (w.equals("")) {
w += i;
}
strings.add(w);
}
return strings;
}
public String helper(int n, int div, String w) {
return n % div == 0 ? w : "";
}