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" ]
<Solution>
這題很直覺,一個 for loop,然後根據條件填相對應的 string 就可以了
這邊有個加速小技巧,在一開始宣告變數時
vector<string> res; => 這樣之後需要花時間來長 vector
vector<string> res(n, ""); => 一次長好長度,並用空字串初始
使用第二個方式,之後可以直接用 index 來 access,而不用使用 push_back 來塞資料
來達到加速的效果
沒有留言:
張貼留言