趣味演算法:返回不重複數的實現

來源:互聯網
上載者:User
BingWay原創作品,轉載請註明作者和出處。 如果一個數字十進位表達時,不存在連續兩位相同,則稱之為“不重複數”。例如,105、164和198都是“不重複數”,而11、100和122不是。下面用一個long類型( long類型數字A),實現返回大於A的最小“不重複數”。 1       static long gNext(long A)
 2       {
 3             long n = A;
 4             int[] a = new int[100];
 5             int cnt = 0;//輸入數的位元
 6             while (n > 0)
 7             {
 8                 a[cnt++] = (int)(n % 10);
 9                 n /= 10;//輸入幾位元執行幾遍
10             }
11             long tmp = 0;//存放臨時值
12             for (int j = cnt-1; j >= 0; j--)//迴圈取值
13             {
14                 tmp = tmp * 10 + a[j];//按高位取值
15                 if (a[j] == a[j + 1])//比較兩個數是否相等
16                 {
17                     tmp = tmp + 1;//比較結果相等則加1
18                 }
19            
20             }
21             if (cnt > 2||tmp>90)////輸入位元大於兩位執行
22             {
23                cnt=1;
24                 for (int i = cnt; i > 0; i--)
25                 {
26                     if (a[i] == a[i - 1])//比較兩個數是否相等
27                     {
28                         tmp = tmp + 1;
29                     }
30                 }
31             }
32             return tmp;
33         }
34         static long getNext(long A)
35         {
36             return gNext(A + 1);
37         }

調用一下getNext(),很簡單,就不寫了。

主函數入口

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.