[英]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... 等等...
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.