Chinaunix首页 | 论坛 | 博客
  • 博客访问: 396572
  • 博文数量: 380
  • 博客积分: 75
  • 博客等级: 民兵
  • 技术积分: 1925
  • 用 户 组: 普通用户
  • 注册时间: 2011-09-05 15:35
文章分类

全部博文(380)

文章存档

2014年(1)

2013年(2)

2012年(19)

2011年(358)

我的朋友

分类:

2011-09-24 11:04:39

原文地址:字符串输出问题 作者:yinyuemi

产生无连续重复部分的字符串。
(1)描述:编写程序,产生由1,2,3这3个数字符号所构成、长度为n的字符串,并且在字符串中对于任何一个子串而言,都不会有相邻的、完全相同的子串;
(2)输入:字符串长度n;
(3)输出:无相邻重复子串的所有字符串,每个字符串换行输出。

思路是“三进制”,此代码的n最大到9。

  1. #include <iostream>
  2. #include <cmath>

  3. using namespace std;

  4. void fun2 (int & p,int & n);

  5. void fun1(int & p, int & n){
  6.     
  7.     p=int(p/10)+1;//进位操作
  8.     n++;
  9.     fun2(p,n);
  10. }

  11. void fun2(int & p, int & n){
  12.     
  13.     if(p%10==4)fun1(p,n);//判断前一位的数字是否需要进位
  14.     else{
  15.         n--;
  16.         p=p*int(pow(double(10),n)); //返回进位后得到的整数值(120,1300等)
  17.     }

  18. }

  19. void if_replicate(int &p){

  20.     int tmp1,tmp2,tmp3,label(1);//tmp1,tmp2用于判断相邻的是否有重复,tmp3暂存p值,label标签
  21.     tmp3=p;
  22.     while(tmp3>10){
  23.         tmp1=tmp3%10;
  24.         tmp3=int(tmp3/10);
  25.         tmp2=tmp3%10;
  26.         if(tmp1==tmp2){label=0;break;}
  27.     }
  28.     if(label){
       
        int count[33]={0};
            int list[10]={0};
            int i(0),j(0);
            tmp3=p;
            while(i++<(10)){
                list[i]=int(tmp3%100);
                count[list[i]]++;
                tmp3=int(tmp3/10);   
            }
            while(j++<10){
                if(list[j]!=0&&count[list[j]]>=2){label=0;break;}
            }
        }
  29.     if(label)
  30.     cout<<p<<endl;    
  31. }

  32. void output(int num){
  33.     
  34.     int k(1),p(0),n(0);
  35.     k=num;
  36.     
  37.     while(num--)p+=int(pow(double(10),num)); //最开始的数字,1111,111,等
  38.     
  39.     if_replicate(p);
  40.     
  41.     while(p<int(pow(double(10),k))){
  42.         p++;
  43.         
  44.         if(p%10==4){//是否需要进位
  45.             n=1;
  46.             fun1(p,n);
  47.             while(n--)p+=int(pow(double(10),n));//尾数赋值,如113-->121,133-->211等
  48.             n=1;}
  49.         if_replicate(p);
  50.     }
  51. }

  52. int main()
  53. {
  54.    int num;
  55.    cout<<"Input a number: ";
  56.    cin>>num;
  57.    output(num);
  58.    return 0;
  59. }

阅读(1059) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~