PAT 1140 C++

1.题意

其实这道题目的意思挺难理解的。

where D is in [0, 9] except 1. The (n+1)st number is a kind of description of the nth number. For example, the 2nd number means that there is one D in the 1st number, and hence it is D1; the 2nd number consists of one D (corresponding to D1) and one 1 (corresponding to 11), therefore the 3rd number is D111; or since the 4th number is D113, it consists of one D, two 1’s, and one 3, so the next number must be D11231. This definition works for D = 1 as well. Now you are supposed to calculate the Nth number in a look-and-say sequence of a given digit D.

上面讲了一堆话,但是其实就是讲了如下几点:

  • 第 n+1 个数其实是对 第n个数的描述信息
    举例:因为第一个数是 D,【有1个D】 => 第二个数是D1
    因为第二个数是D1【有一个D;有1个1】 => 第三个数是D111
    因为第三个数是D111【有一个D;有三个1】 => 第四个数是D113
    ···
    现在给你一个数字D,让你求出第N个输出的数是什么。

2.分析

简单的字符串处理题。需要注意一下的时候可能因为数组开的不够大导致段错误 的发生。

3.代码

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
using namespace std;
 
#define maxn 100000

char res[maxn];
char ori[maxn];
 
//针对 ori[maxn] 这个字符串得到新的字符串 
int getRes(char ori[],int seq){
	int i,count,time = 1,index =1 ;
	int length ;
	char curChar;
	char tempStr[maxn];
	
	while(time < seq){
		index = 0;
		length = strlen(ori);
		for(i = 0;i < length; i++){			
			curChar = ori[i];
			count = 0;
			while(curChar == ori[i] && i < length){
				count ++;
				i++;		
			}
			i--;
			tempStr[index++] = curChar;
			tempStr[index++] = count+48;			
		}
		time ++;
		//将tempStr 的值赋给 ori 
		for(i = 0;i < index;i++){
			ori[i] = tempStr[i];						
		}
	}
	
	for(i = 0;i < index;i++){		
		cout <<  ori[i];
	}cout<<"\n";
}

int main(){
	int digit,seq;
	scanf("%d%d",&digit,&seq);
	ori[0] = digit + 48;
	getRes(ori,seq);
	
} 

4.测试用例

1 40

5.执行结果

PAT 1140 C++ 版

相关文章: