当前位置 : 主页 > 手机开发 > ROM >

Lintcode9-Fizz Buzz-Easy

来源:互联网 收集:自由互联 发布时间:2021-06-10
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 and 5 , print "fizz buzz" . when number can‘t be divided


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 and 5, print "fizz buzz".
  • when number can‘t be divided by either 3 or 5, print the number itself.

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?

 

注意:

  1. 同时被3和5整除,应该是 num % 15 == 0 , 而不是 nums % 3 == 0 && nums % 5 == 0 , 后者会加长运行时间。
  2. 四种情况的判断顺序很重要,同样影响运行时间。采用 "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.
  3. Java int -> String : String s = String.valueOf(i);
  4. 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     }
网友评论