Created
September 11, 2013 09:04
-
-
Save ETiV/6521105 to your computer and use it in GitHub Desktop.
给定一个数X,他的兄弟数Y定义为:是由X中的数字组合而成,并且Y是大于X的数中最小的。例如,38276的兄弟数字为38627。给定X,求Y。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var find_next_max = function (num) { | |
var _result = '', _arr = num.toString().split(''); | |
// 从 _arr 里找到比 num 首位大的最小的数 | |
// 因为 _arr 里的数字都是个位数, 所以返回 10 的话, 表示找不到 | |
var find_number_larger_than_first_pos = function () { | |
var first, n = 10, _num; | |
for (var i in _arr) { | |
_num = parseInt(_arr[i]); | |
if (i == 0) { | |
first = _num; | |
} else { | |
if (n >= _num && _num > first) { | |
n = _num; | |
} | |
} | |
} | |
return n; | |
}; | |
// 从剩余的 _arr 里找到一个最小的数 | |
var find_next_min = function () { | |
var n = 10; | |
for (var i in _arr) { | |
if (n >= parseInt(_arr[i])) { | |
n = parseInt(_arr[i]); | |
} | |
} | |
return n; | |
}; | |
// 找不到比首位更大的数 | |
if (find_number_larger_than_first_pos() == 10) { | |
return false; | |
} else { | |
var _new_first = find_number_larger_than_first_pos(); | |
_arr.splice(_arr.indexOf(_new_first.toString()), 1); | |
_result += _new_first.toString(); | |
do { | |
var _next_min = find_next_min(); | |
_arr.splice(_arr.indexOf(_next_min.toString()), 1); | |
_result += _next_min.toString(); | |
} while (_arr.length > 0); | |
} | |
return _result; | |
}; | |
var find_brother = function (x) { | |
var _str = x.toString(); | |
for (var i = 2; i <= _str.length; i++) { | |
var _find = _str.substr(_str.length - i, i); | |
var result = find_next_max(parseInt(_find)); | |
if (result != false) { | |
console.log(_str.substr(0, _str.length - i), result); | |
break; | |
} | |
} | |
}; | |
find_brother(123); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment