Count and say

Source: Internet
Author: User
The count-and-say sequence is the sequence of integers beginning as follows:

1, 11, 21, 1211, 111221, ...

1Is read off"one 1"Or11.
11Is read off"two 1s"Or21.
21Is read off"one 2, Thenone 1"Or1211.

Given an integerN, GenerateNTh sequence.

Note: The sequence of integers will be represented as a string.

 

Train of Thought: the number of times each character in a string is counted, and the next one needs to be obtained based on the previous one. Therefore, two strings are required.

The maximum value of time is 3, because if two different values are combined, for example, 12 -- "1112, and two identical values are 11 --" 21.

Class solution {public: Char myitoa (int A) {return a + '0';} string countandsay (int n) {string S = "1"; string res; int time = 1; if (n = 1) return s; while (n-1) {-- N; Res. clear (); int Len = S. size (); For (INT I = 0; I <Len; ++ I) {if (I! = Len-1 & S [I] = s [I + 1]) + + time; else {res. push_back (myitoa (time); // time is a number and Res. push_back (s [I]); time = 1 ;}} S. clear (); s = res;} return res ;}};

 

Count and say

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.