int转string与LeetCode:Count and Say

来源:互联网 发布:nx三维软件 编辑:程序博客网 时间:2024/05/10 09:04

int转string


Reference:http://www.cnblogs.com/nzbbody/p/3504199.html

string流的使用:

#include <iostream>#include <string>#include <sstream>using namespace std;int main(){    string str{"is"};    int a;    cin>>a;    stringstream ss;    ss<<a;    str+=ss.str();    cout << str<<endl//输入12显示is12            <<"Hello world!" << endl;    return 0;}

这里写图片描述


LeetCode:Count and Say

1、题目:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, …

1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n, generate the nth sequence.

2、代码:

class Solution {public:    string countAndSay(int n) {        vector<string> cas(1,"1");        while(cas.size()<n)        {            string str{cas.back()},say{};            int count=0;            char c=str[0];            for(const char &cm:str)            {                if(c==cm)                {                    ++count;                }                else                {                    string cstr{c};                    stringstream ss;                    ss<<count;                    say+=(ss.str()+cstr);                    c=cm;                    count=1;                }            }            string cstr{c};            stringstream ss;            ss<<count;            say+=(ss.str()+cstr);            cas.push_back(say);        }        return cas.back();    }};

3、总结:
以为不会过的,但是他竟然过了。
A、int转string
B、.back()函数获取尾值

0 0
原创粉丝点击