Answers for "find the next smaller number with the same digits"

0

find the next smaller number with the same digits

// Find the next smaller number with the same digits

fn next_smaller_number(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_number(531));  //  Some 513
    println!("{:#?} ", next_smaller_number(0));    //  None 
}
Posted by: Guest on September-08-2021

Code answers related to "find the next smaller number with the same digits"

Browse Popular Code Answers by Language