LeetCode题解:FizzBuzz

    xiaoxiao2021-03-26  24

    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”.

    Example:

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

    思路:

    太简单。

    题解:

    std::vector<std::string> fizzBuzz(int n) { std::vector<std::string> result(n); for(int i = 1; i <= n; ++i) { if (i % 3 && i % 5) result[i - 1] = std::to_string(i); else if (i % 3) result[i - 1] = "Buzz"; else if (i % 5) result[i - 1] = "Fizz"; else result[i - 1] = "FizzBuzz"; } return result; }

    转载请注明原文地址: https://ju.6miu.com/read-658331.html

    最新回复(0)