Next smaller number with the same digits (4kyu)

Next smaller number with the same digits (4kyu)

Description

Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits.

For example:

next_smaller(21) == Some(12)
next_smaller(531) == Some(513)
next_smaller(2071) == Some(2017)

Return -1 (for Haskell: return Nothing, for Rust: return None), when there is no smaller number that contains the same digits. Also return -1 when the next smaller number with the same digits would require the leading digit to be zero.

next_smaller(9) == None
next_smaller(135) == None
next_smaller(1027) == None  // 0721 is out since we don't write numbers with leading zeros
  • some tests will include very large numbers.
  • test data only employs positive integers.

Solution

The step of finding next smaller number:

take num = 32514 as an example

  1. Find the position i of the first digit from lower to upper place that is smaller than its right dight, got i=3 .
  2. If i==0 , the num has no next smaller number.
  3. Find the position j of the first digit that is smaller that num[i-1] , which is 5, got j = 4 .
  4. Swap ( i-1 , j ), got 32415 .
  5. Reverse the digits to the right of i-1 , got 32451 .
  6. Check the length of the result. Return None if it’s not equal to num.len() .
fn next_smaller_number(n: u64) -> Option<u64> {
    let mut digits: Vec<u64> = n.to_string().chars().map(|d| d.to_digit(10).unwrap() as u64).collect();
    let mut i = digits.len() - 1;
    while i > 0 && digits[i - 1] <= digits[i] { // find first digit that is smaller than the digit to its right
        i -= 1;
    }
    if i == 0 {
        return None;
    }
    let mut j = digits.len() - 1;
    while digits[j] >= digits[i - 1] { // find the smallest digit to the right of i - 1 that is larger than it
        j -= 1;
    }
    digits.swap(i - 1, j);
    digits[i..].reverse();
    let result = digits.iter().fold(0, |acc, &d| acc * 10 + d);
    if result == 0 {
        None
    } else {
        if result.to_string().len() != digits.len() {
            return None;
        }
        Some(result)
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值