Share my simple c++ code with 0 ms


  • 0
    D
    class Solution {
    public:
        string countAndSay(int n) 
    	{
    		string str = "1",res;
    		for(int k=2; k<=n; ++k)
    		{
    			int num = 1;
    			for(int i=0; i<str.size(); ++i)
    			{
    				char text = str[i];
    				if(i+1 < str.size() && text == str[i+1])
    					++num;
    				else
    				{
    					res.push_back(num+'0');
    					res.push_back(text);
    					num = 1;
    				}
    			}
    			str = res;
    			res.clear();
    		}
    		return str;
    	}
    };

  • 0
    H

    It would be wrong answer when "num" exceed 9.


  • 0
    D

    thanks! you said is right, however, it will not happen when "num" exceed 9 !
    for example: if N-th : 1111111111 , it means the (n-1)Th is 11111. Actually, it returns 51 in nth. so it will not happen when "num" exceed 9 .


  • 0
    H

    Yes, that's right ~
    N will be extremly large to form a "11111111111".


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.