Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUST

Find the next smaller positive integer containing the same digits

// Find the next smaller positive integer containing the same digits
// Example: next_smaller(2071) gives 2017 as answer

fn next_smaller(n: u64) -> Option<u64> {
    let mut v: Vec<_> = n.to_string().chars().collect();
    let mut i = v.len() - 1;
    while i != 0 && v[i] >= v[i - 1] {
        i -= 1;
    }
    if i == 0 {
        return None;
    } 
    let mut a = v.len() - 1;
    while v[a] >= v[i - 1] {
        a -= 1;
    }
    if v[a] == '0' && i == 1 {
        return None;
    }
    v.swap(a, i - 1);
    v[i..].sort();
    v[i..].reverse();
    Some(v.iter().collect::<String>().parse().unwrap())
}

fn main() {
	println!("{:?}", next_smaller(2071) );  // 2017
}
 
PREVIOUS NEXT
Tagged: #Find #smaller #positive #integer #digits
ADD COMMENT
Topic
Name
5+1 =