<Interview Problem>最小的“不重复数”

百度的一道笔试题目,看到博客园讨论挺热烈的,也写一下玩玩。

实现思想:举个简单的例子11233,从高位到低位开始判断是否有重复数,高位有重复数后,首先修改高位的,高位修改后变为12233,因为要求最小的不

重复数,这时实际上要求的是12000这个数的最小不重复数了。在举个例子98989899,它的变化系列可是是这样:

98989900
98990000
99000000
100000000
101000000
101010000
101010100
101010101

1、给定任意一个正整数,求比这个数大且最小的“不重复数”,“不重复数”的含义是相邻两位不相同,例如1101是重复数,而1201是不重复数。

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 
 5 using namespace std;
 6 
 7 int test(int n){
 8         char str[32];
 9         sprintf(str,"%d",n);
10         int len = strlen(str);
11         int cur = 0;
12         int next = 1;
13         if(len < 2)
14                 return -1;
15         for(int i = 0; i < len; i++)
16         {
17                 cur = i;
18                 next = i+1;
19                 if(str[cur] == str[next]){
20                         int result = len - (i+1);
21                         return result;
22                 }
23                 if(next == len)
24                         break;
25         }
26         return -1;
27 }
28 int find(int n)
29 {
30         int pos = test(n);
31         if(pos == -1)
32                 return n;
33         else{
34                 int step = 1;
35                 for(int i = 1; i < pos; i++)
36                         step *= 10;
37                 cout << n/step*step+step <<endl;
38                 find(n/step*step+step);
39         }
40 }
41 
42 int main(){
43 
44         int n = 12345;
45         cout << test(12345) << ": " << find(12345) << endl;
46         cout << test(11233) << ": " << find (11233) << endl;
47         cout << test(11) <<": " << find(11) <<  endl;
48         cout << test(199) << ": " << find(199) <<  endl;
49         cout << "1099012: "<<find(1099012)<<endl;
50         cout << "11234: "<<find(11234)<<endl;
51         cout << "98989899: "<<find(98989899)<<endl;
52         cout << "10989899: "<<find(10989899)<<endl;
53         return 0;
54 
55 }
View Code

测试结果如下:

-1: 12345
4: 12010
1: 12
1: 201
1099012: 1201010
11234: 12010
98989899: 101010101
10989899: 12010101

原文地址:https://www.cnblogs.com/cstar/p/3355656.html