表示,不知道怎么用java表示 while(cin >> n) 。。。
好像上次的办法不奏效了。 再贴个cpp的 给大家另外的思路吧
“伯爵说”序列如下:1, 11, 21, 1211, 111221, ...1 is 读作 "one 1" 或者 11.11 is 读作 "two 1s" 或者21.21 is 读作 "one 2, one 1" 或者 1211.
格式:给定一个整数n,输出第n个序列。
注意:整数序列以字符串的形式表示。
PS:相信你已经看懂了题目,如果没看懂,小提示下,
其实类似于求”菲波拉契“数列的第n项哦~
样例输入
6
样例输出
312211
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while( in.hasNext()){
int n= in.nextInt();
int[] num = new int[1000];
int[] temp = new int[1000];
Arrays.fill(num, -1);
Arrays.fill(temp, -1);
int i,j,count=0;
num[0]=1;
num[1]=1;
temp[0]=1;
if(n==1)
System.out.println("1");
else{
for(j=1;j<n-1;j++){
for(i=1;num[i]!=-1;i++){
if(num[i]!=num[i-1])
{count++;
temp[count]=num[i-1];
if(num[i+1]==-1)
{
count++;
temp[count]=1;
count++;
temp[count]=num[i];
}
else{
count++;
temp[count]=1;
}
}
else if(num[i]==num[i-1])
{temp[count]++;
if(num[i+1]==-1)
temp[count+1]=num[i];
}
}
for(i=0;temp[i]!=-1;i++)
num[i]=temp[i];
Arrays.fill(temp, -1);
temp[0]=1;
count=0;
}
for(i=0;num[i]!=-1;i++)
{
if(num[i+1]==-1)
System.out.println(num[i]);
else
System.out.print(num[i]);}
}
}
}
}
#include<iostream>
using namespace std;
string result[100];
string str(string s) { //具体的转换函数
string a = "";
int l = s.length(), i, j, m;
for (i = 0; i < l; i = i + m) {
m = 1;
for (j = i + 1; j < l; j++) {
if (s[i] == s[j])
m++;
else
break;
}
char c = m + '0';
a.push_back(c);
a.push_back(s[i]);
}
return a;
}
string rec(int n) { //动态规划函数
string res;
if(result[n] != "")
return result[n];
if (n == 1)
res = "1";
else
res = str(rec(n - 1));
return res;
}
int main() {
int n;
while(cin >> n)
cout << rec(n) << endl;
}