整型轉換成string的問題

題目來源:

點擊打開鏈接


題目描述:

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"
]


我的解決方案:

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> ret;
        for(int i=1;i<=n;++i)
        {
            if(i%3==0)
            {
                if(i%5==0)
                  ret.push_back("FizzBuzz");
                else
                  ret.push_back("Fizz");
            }
            else if(i%5==0)
                ret.push_back("Buzz");
            else
            {
              stringstream ss;
              string s;
              ss<<i;
              ss>>s;
              ret.push_back(s);
            }
        }
        return ret;
    }
};


思考:
這道題目本身很簡單,沒啥好說的,比較有意思的一點就是整型轉換爲string.因爲string的構造函數是不支持直接從int轉換爲string的,最開始的時候嘗試過定義一個臨時的char變量,然後強行等於這個整型,再轉換成string發現還是不行(其實可以用char數組,然後sprint的方式來轉換),最後google了一下,選擇了stringstream的流的方式來進行轉換,確實很方便.從字符串轉換爲整型就比較方便了,atoi函數就可以


發佈了31 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章