Fizz Buzz

作者: 小呀么小黄鸡 | 来源:发表于2019-07-31 23:46 被阅读0次

问题描述

https://www.lintcode.com/problem/fizz-buzz/description?_from=ladder&&fromId=6

lintcode-简单-Fizz Buzz问题,只用一个if语句

只能用一个if语句,所以不能是先判断再填字符,应该要先在每个位置把字符填进去,然后遇到3的倍数把数字改了,改成fizz,3的倍数改完去改5的倍数,这时候就需要判断一下这个5的倍数是否同时也是3的倍数是的话就在后面补一个单词,不是就改。按着这样的思路试了一下:

class Solution {
public:
    /*
     * @param n: An integer
     * @return: A list of strings.
     */
    vector<string> fizzBuzz(int n) {
        // write your code here
        vector<string> temp;
        string str;
        
        for(int i=1;i<=n;++i)
        {
            stringstream ss;
            ss<<i;
            str=ss.str();
            temp.push_back(str);
        }
        for(int j=1;(3*j)<=n;++j)
        {
            temp[3*j-1]="fizz";
        }
        for(int k=1;(5*k)<=n;++k)
        {
            if(5*k%3==0)
            {
                temp[5*k-1]=temp[5*k-1]+" "+"buzz";
            }
            else
            {
                temp[5*k-1]="buzz";
            }
        }
        return temp;
    }
};
--------------------- 
作者:weixin_41670996 
来源:CSDN 
原文:https://blog.csdn.net/weixin_41670996/article/details/79150889 
版权声明:本文为博主原创文章,转载请附上博文链接!

js实现

const fizzBuzz = function (n) {
    let arr = [];
    for (var i = 1; i <= n; i++) {
        arr.push(i+"");
    }
    for (var j = 1; j * 3 <= n; j++) {
        arr[j*3-1] = "fizz";
    }
    for (var k = 1; k * 5 <= n; k++) {
        if(k * 5 % 3 != 0) {
            arr[k*5-1] = "buzz";
        } else {
            arr[k*5-1] = "fizz buzz";
        }
    }
    return arr;
}

相关文章

  • LeetCode 411-430

    412. Fizz Buzz[https://leetcode-cn.com/problems/fizz-buzz...

  • Leetcode PHP题解--D40 412. Fizz Bu

    412. Fizz Buzz 题目链接 412. Fizz Buzz 题目分析 这个题目也很简单。 从1逐个输出到...

  • Day 2: Prepare For FizzBuzz.z ->

    Fizz Buzz in Tensorflow interviewer: Welcome, can I get y...

  • 【LeetCode】Fizz Buzz 解题报告

    【LeetCode】Fizz Buzz 解题报告 [LeetCode] https://leetcode.com/...

  • 【LeetCode】Fizz Buzz 解题报告

    【LeetCode】Fizz Buzz 解题报告 [LeetCode] https://leetcode.com/...

  • Fizz Buzz

    写一个程序,输出从 1 到 n 数字的字符串表示。 如果 n 是3的倍数,输出“Fizz”; 如果 n 是5的倍数...

  • Fizz Buzz

    Write a program that outputs the string representation of...

  • Fizz Buzz

    问题描述 https://www.lintcode.com/problem/fizz-buzz/descripti...

  • Fizz Buzz

    写一个程序,输出从 1 到 n 数字的字符串表示。 如果 n 是3的倍数,输出“Fizz”; 如果 n 是5的倍数...

  • Fizz Buzz

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/fizz-b...

网友评论

      本文标题:Fizz Buzz

      本文链接:https://www.haomeiwen.com/subject/weffdctx.html