Search
 
SCRIPT & CODE EXAMPLE
 

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
}
Comment

PREVIOUS NEXT
Code Example
Rust :: rustlang how to edit project names 
Rust :: armanriazi•rust•error•E0277•the size for values of type `str` cannot be known at compilation time 
Rust :: Take two integers, return the quotient and remainder, divmod 
Rust :: armanriazi•rust•static 
Rust :: armanriazi•rust•oop 
Rust :: rust `cfg` which is always true / false 
Rust :: rust absolute path 
Rust :: rust•armanriazi•test•mock 
Rust :: armanriazi•rust•unsafe•function•or•method 
Rust :: Vector with multiple types in rust 
Rust :: armanriazi•substrate•call•dispatchable•func#ensure_signed#frame_system 
Rust :: armanriazi•rust•error•E0277•the trait bound `` is not satisfied 
Rust :: armanriazi•rust•concept•coherence 
Lua :: roblox studio teleport on touch 
Lua :: lerp lua 
Lua :: luau how to make a kill brick 
Lua :: roblox tween color3 
Lua :: roblox how to find something in table 
Lua :: lua gsub 
Lua :: how to get the length of a table in lua 
Lua :: string.match roblox 
Lua :: how to split strings into 2 string by space lua 
Lua :: table lua 
Lua :: how to format a number into hh:mm:ss in lua 
Lua :: the function returning the address of a local variable results in: 
Lua :: roblox lua 
Matlab :: count even and odd numbers in matlab 
Matlab :: matlab tf get poles 
Basic :: what to include in basic C 
Elixir :: elixir string to atom 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =