简体   繁体   English

将n位数字减少到最低值

[英]Reduce n-digit number to its lowest possible value

This seems trivial but I'm baffled that I haven't been able to come to a solution on this. 这看似微不足道,但令我感到困惑的是,我无法对此提出解决方案。 What I'm trying to do is: 我想做的是:

Input ->  14025
Output -> 10245

Input ->  171
Output -> 117

And so on... 等等...

$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 演示

A bit more verbose, but similar to previous answer 较为详细,但与先前的答案类似

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM