给定一个正数num,要返回一个大于num的数,并且每一位和相邻位的数字不能相等.
返回达标的数字中,最小的那个。
从左往右看,是否有相邻两位相同的数字。如果有,则低位加1,低位右边全变成0,递归。
代码用rust编写。代码如下:
fn main() {
let answer = near(766665);
println!("answer = {}", answer);
}
fn near(num: isize) -> isize {
// num = 174
// "0175"
// num = 899
// "0900"
// num = 999
// "01000"
let mut raw = format!("0{}", num + 1).chars().collect::<Vec<_>>();
process(&mut raw);
return raw.iter().collect::<String>().parse::<isize>().unwrap();
}
fn process(raw: &mut Vec<char>) {
for i in 1..raw.len() {
if raw[(i - 1) as usize] == raw[i as usize] {
add_one(raw, i as isize);
for j in i + 1..raw.len() {
raw[j as usize] = '0';
}
process(raw);
return;
}
}
}
// 99.....
// +1
//100
fn add_one(r: &mut Vec<char>, i: isize) {
let mut i: isize = i;
while r[i as usize] == '9' {
r[i as usize] = '0';
i -= 1;
}
r[i as usize] = (r[i as usize] as u8 + 1) as char;
}
执行结果如下: