Fizz Buzz
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
and5
, print"fizz buzz"
. - when number can't be divided by either
3
or5
, print the numberitself
.
Example
If n = 15, you should return:
[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz", "11", "fizz",
"13", "14", "fizz buzz"
]
If n = 10, you should return:
[
"1", "2", "fizz",
"4", "buzz", "fizz",
"7", "8", "fizz",
"buzz"
]
Challenge
Can you do it with only one if
statement?
注意:
- 同时被3和5整除,应该是 num % 15 == 0 , 而不是 nums % 3 == 0 && nums % 5 == 0 , 后者会加长运行时间。
- 四种情况的判断顺序很重要,同样影响运行时间。采用 "if - else if - else if - else": if (num % 15 == 0)- else if (num % 5 == 0) - else if (num % 3 == 0) - else. else if 对判断先后顺序有要求,不可颠倒。而如果全部是if, 每个if判断的条件会增加,即增加运行时间。if (num % 15 == 0)- if (num % 5 == 0 && num % 3 != 0) -if (num % 3 == 0 && num % 5 != 0) - else.
- Java int -> String : String s = String.valueOf(i);
- List.add() 参数只能是字符串,所以 line 13.
代码:
1 public List<String> fizzBuzz(int n) { 2 int num = 1; 3 List<String> fblist = new ArrayList<String>(); 4 5 while (num <= n){ 6 if (num % 15 == 0) { 7 fblist.add("fizz buzz"); 8 } else if (num % 5 == 0) { 9 fblist.add("buzz"); 10 } else if (num % 3 == 0) { 11 fblist.add("fizz"); 12 } else { 13 fblist.add(String.valueOf(num)); 14 } 15 num++; 16 } 17 return fblist; 18 }