[Leetcode从零开刷]412. Fizz Buzz

题目来源:
leetcode
Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

翻译:写一个程序,能根据数字1到n输出不同的字符串。
数字是3的倍数时输出Fizz,是5的倍数时输出Buzz,同时是3和5的倍数时输出FizzVBuzz

举例:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]

java写法:

class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> rev = new ArrayList<String>(n);
        for(int i = 1,fizz =0,buzz =0;i<=n;i++)
        {
            fizz++;
            buzz++;
            if(fizz ==3 && buzz ==5 )
            {
                rev.add("FizzBuzz");
                fizz=0;
                buzz=0;
            }
            else if(fizz==3)
            {
                rev.add("Fizz");
                fizz=0;
            }
            else if(buzz==5)
            {
                rev.add("Buzz");
                buzz=0;
            }
            else
            {
                rev.add(String.valueOf(i));
            }                
        }
        return rev;

    }
}

python:

class Solution:
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]

python这个写法很厉害啊
马上有类似的Java写法如下:

private String FIZZ = "Fizz";
private String BUZZ = "Buzz";
private String FIZZ_BUZZ = "FizzBuzz";

public List<String> fizzBuzz(int n) {
    List<String> res = new ArrayList();
    for(int i = 1; i <= n; i++){
        //remove if else, make code shorter
        String temp = i % 15 == 0 ? FIZZ_BUZZ : (i % 3 == 0 ? FIZZ : (i % 5 == 0 ?  BUZZ : String.valueOf(i)));
        res.add(temp);
    }
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值