【问题标题】:Reduce n-digit number to its lowest possible value将 n 位数减少到可能的最低值
【发布时间】:2017-12-11 12:41:01
【问题描述】:

这似乎微不足道,但我很困惑,我无法找到解决方案。我想做的是:

Input ->  14025
Output -> 10245

Input ->  171
Output -> 117

等等……

【问题讨论】:

  • 计算所有排列,加入数组并排序?
  • @DarkBee 好主意...让我看看进展如何
  • @Kaddath 是的,但是以 0 开头的数字在现实世界中并不适用。我必须保持位数等 01245 != 1245
  • 这是一个以TDD开头的完美示例

标签: php


【解决方案1】:
$input = 140205;

$temp = str_split($input);
sort($temp);
// find the 1st non-zero digit
$f = current(array_filter($temp));
// remove it from the array
unset($temp[array_search($f, $temp)]);
echo $output = $f . join($temp);  // 100245

demo

【讨论】:

  • 这是一个不错的方法
  • 我从评论部分的建议中找到了自己的方法。但我会继续将此标记为已接受的答案,因为这绝对是比我更好的解决方案。为了其他人的信息,我也会发布我的。
  • 很高兴为您提供帮助。祝你好运!
【解决方案2】:

有点冗长,但与之前的答案类似

function smallestNumberFromDigits($string) {
    //split string to digits
    $array = str_split($string);
    //sort the digits
    sort($array);

    //find the first digit larger than 0 and place it to the begining of array
    foreach($array as $i => $digit) {
        if($digit > 0) {
            $tmp = $array[0];
            $array[0] = $digit;
            $array[$i] = $tmp;
            break;
        }
    }

    //return the imploded string back
    return implode("", $array);
}

【讨论】:

    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2015-11-17
    • 2019-04-27
    相关资源
    最近更新 更多