百度的一道筆試題目,看到博客園討論挺熱烈的,也寫一下玩玩。ios
實現思想:舉個簡單的例子11233,從高位到低位開始判斷是否有重複數,高位有重複數後,首先修改高位的,高位修改後變爲12233,由於要求最小的不ide
重複數,這時實際上要求的是12000這個數的最小不重複數了。在舉個例子98989899,它的變化系列但是是這樣:測試
98989900
98990000
99000000
100000000
101000000
101010000
101010100
101010101spa
一、給定任意一個正整數,求比這個數大且最小的「不重複數」,「不重複數」的含義是相鄰兩位不相同,例如1101是重複數,而1201是不重複數。code
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 }
測試結果以下:blog
-1: 12345
4: 12010
1: 12
1: 201
1099012: 1201010
11234: 12010
98989899: 101010101
10989899: 12010101博客