LintCode刷题(九):fizz and buzz

复习了半个多月的考试,心力交瘁。继续更新

描述
给你一个整数n. 从 1 到 n 按照下面的规则打印每个数:
如果这个数被3整除,打印fizz.
如果这个数被5整除,打印buzz.
如果这个数能同时被3和5整除,打印fizz buzz.

C++:

class Solution {
public:
    /**
     * @param n: An integer
     * @return: A list of strings.
     */
    vector<string> fizzBuzz(int n) {
        // write your code here
        vector<string> res; //容器
        for(int i=1;i<=n;i++)
        {
            if(i%15==0)
            {
                res.push_back("fizz buzz");
            }
            else if (i%3==0)
            {
                res.push_back("fizz");
            }
            else if (i%5==0)
            {
                res.push_back("buzz");
            }
            else
            {
                res.push_back(to_string(i)); //C++11才有的to_string
            }

        }

        return res;
    }
};

Py3 :

class Solution:
    """
    @param n: An integer
    @return: A list of strings.
    """
    def fizzBuzz(self, n):
        # write your code here

        res = []

        #还是要注意range的用法
        for i in range(1,n+1):
            if i%3 == 0 and i%5 == 0:
                res.append("fizz buzz")

            elif i%3 == 0:
                res.append("fizz")

            elif i%5 == 0 :
                res.append("buzz")

            else:
                res.append(str(i))

        return res

猜你喜欢

转载自blog.csdn.net/qq_38213612/article/details/80577754
今日推荐