閱讀240 返回首頁    go 阿裏雲 go 技術社區[雲棲]


給出任意一個正整數,算出大於它的最小不重複數——最高效[2014百度筆試題]

程序很簡單,一看就懂,我就不多介紹了,直接上代碼。

/**
 * 給出任意一個正整數,算出大於它的最小不重複數(即不存在相鄰兩個數相同的情況)
 */
#include<iostream>

using namespace std;

long minNoDoubleNumber(long x) {
	if(x < 10) {
		return x;
	}

	long y = 1;
	long temp = x;
	while(temp / 10 > 0) {
		y *= 10;
		temp /= 10;
	}
	y /= 10;

	int next = -1;
	bool hasPlus = false;
	while(y > 0) {
		next = (x / 10 / y) % 10;
		if((x / y) % 10 == next) {
			if(!hasPlus) {
				x += y;
				hasPlus = true;
				if(9 == next) {
					return minNoDoubleNumber(x);
				}
			} else {
				x -= y;
				if(0 == next) {
					return minNoDoubleNumber(x);
				}
			}
		} else {
			y /= 10;
		}
	}
	return x;
}

int main(void) {
	long x;
	cout<<"x=";
	cin>>x;
	cout<<"result="<<minNoDoubleNumber(x)<<endl;
}


程序文件見:https://github.com/wenin819/wenin819/blob/master/src/number/min_no_double_number.cpp

最後更新:2017-04-03 14:54:25

  上一篇:go 手機衛士07-設置向導
  下一篇:go 龐果網之尋找直方圖中麵積最大的矩形