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

9. Fizz Buzz 问题

来源:互联网 收集:自由互联 发布时间:2021-06-10
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 retur

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?

public class Solution {
    /**
     * @param n: An integer
     * @return: A list of strings.
     */
    public List<String> fizzBuzz(int n) {
        // write your code here
        List<String> res = new ArrayList<>();
            
        for(int i=1;i<n+1;i++){
            if(i % 15 == 0){
                res.add("fizz buzz");
                
            }else if( i % 3 ==0){
                res.add("fizz");
            
                
            }else if( i % 5 == 0){
                res.add("buzz");
            
                
            }else{
                res.add(i + "");
            }
        }
        return res;
    }
}
描述
给你一个整数n. 从 1 到 n 按照下面的规则打印每个数:

如果这个数被3整除,打印fizz.
如果这个数被5整除,打印buzz.
如果这个数能同时被3和5整除,打印fizz buzz.
您在真实的面试中是否遇到过这个题?  
样例
比如 n = 15, 返回一个字符串数组:

[
  "1", "2", "fizz",
  "4", "buzz", "fizz",
  "7", "8", "fizz",
  "buzz", "11", "fizz",
  "13", "14", "fizz buzz"
]
网友评论