2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個贊
您需要從最大的值開始兌換,直到您的金額小于最大的紙幣(例如 2000)。然后你用更低的音符(例如500)做同樣的事情,然后再用更低的音符。當(dāng)金額小于最低值(例如 20)時,您無法兌換此金額。
所以:
我們從2270開始
我們檢查最大的紙幣 - 它是 2000。
現(xiàn)在我們知道我們有 2000 和 270 (2270 - 2000) 休息
現(xiàn)在我們再次檢查最大值 - 它是 200
所以我們有 2000、200 和 70 (270 - 200) 休息
現(xiàn)在最大的不可能是 50
所以我們有 2000, 200, 50 和 20 (70 - 50) 休息
現(xiàn)在最大的是 20,我們有 2000、200、50、20,其余的是 0
由于休息比最低音符小,所以我們可以停止檢查。
如果 rest 為 0,我們知道我們可以交換,如果 rest 大于 0,則我們不能。此外,我們還有可用于交換的票據(jù)列表(2000、200、50、20)。
function checkDenomination($amount){
$notes = array(2000,500,100,50,20); //it's easier if they are reversed
$smallestNote = 20;
$result = [];
while($amount >= $smallestNote) { //we will repeat until we can exchange
foreach($notes as $note) {
if ($amount >= $note) { //we check for largest value we can exchange
$result[] = $note;
$amount -= $note; //as we have hit, we can deduct it from amount;
break;
}
}
}
return ($amount > 0) ? false : $result; //return false if we cannot exchange this amount or array with notes we can exchange for full amount
}
var_dump(checkDenomination(100));
var_dump(checkDenomination(23424));
var_dump(checkDenomination(25000));
var_dump(checkDenomination(222));

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個贊
嘗試兩個模塊化部門
function validateCurrency($amount)
{
$requestdAmount = $amount;
$valueUnder = 0;
$notes = array(20, 50,100,500,2000);
$is_allowed = 0;
if(in_array($amount, $notes)){
return $is_allowed = 1;
}
$numOccurance = ceil($amount/$notes[0]);
$arraySums = [];
foreach ($notes as $key => $value) {
for ($i=1; $i <= $numOccurance; $i++) {
if($value * $i == $amount) {
return $is_allowed = 1;
}
$arraySums[$key][] = $value * $i;
}
}
for ($i=0; $i < count($arraySums); $i++) {
for ($j=$i+1; $j < count($arraySums); $j++) {
foreach ($arraySums[$i] as $key => $value) {
foreach ($arraySums[$j] as $key2 => $toBeMul) {
if($value+$toBeMul == $amount) {
return $is_allowed = 1;
}
}
}
}
}
return $is_allowed;
}
// Driver Code
$amount = 40;
$is_allowed = validateCurrency($amount);
echo $is_allowed;
die();
它會工作
- 2 回答
- 0 關(guān)注
- 169 瀏覽
添加回答
舉報