1. 程式人生 > >LintCode-Fizz Buzz問題

LintCode-Fizz Buzz問題

  1. 描述
    給你一個整數n. 從 1 到 n 按照下面的規則列印每個數:
    如果這個數被3整除,列印fizz.
    如果這個數被5整除,列印buzz.
    如果這個數能同時被3和5整除,列印fizz buzz.
  2. 樣例
    比如 n = 15, 返回一個字串陣列:
    [
    “1”, “2”, “fizz”,
    “4”, “buzz”, “fizz”,
    “7”, “8”, “fizz”,
    “buzz”, “11”, “fizz”,
    “13”, “14”, “fizz buzz”
    ]
  3. 程式碼
class Solution {
public:
    /**
     * param n: As description.
     * return: A list of strings.
     */
vector<string> fizzBuzz(int n) { vector<string> results; for(int i=1;i<=n;i++) { if(i%5==0&&i%3==0) results.push_back("fizz buzz"); else if(i%5==0) results.push_back("buzz"); else if(i%3
==0) results.push_back("fizz"); else results.push_back(to_string(i)); } return results; } };