100銅幣=1銀 100銀=1金
想寫個根據多少銅幣 返回相應等級的錢
比如參數為102135銅幣
那就是返回10金21銀35銅
比如參數為1544銅幣
那就是返回15銀44銅
以此類推...
php基礎不紮實 不知道怎麼寫最精簡
回複內容:
100銅幣=1銀 100銀=1金
想寫個根據多少銅幣 返回相應等級的錢
比如參數為102135銅幣
那就是返回10金21銀35銅
比如參數為1544銅幣
那就是返回15銀44銅
以此類推...
php基礎不紮實 不知道怎麼寫最精簡
/** * [format_every 換算進位到指定單位] * @param integer $number [需要換算數值] * @param integer $ary [每個單位之間的進位] * @param array $units [每個單位的描述] * @return [String] [格式化結果] */function format_every($number,$ary = 100,$units = array('銅', '銀', '金')) { $format = ''; $prev = 0; for($i = count($units) - 1 ; $i >= 0 ; $i--){ if($next = floor($number / pow($ary, $i))){ $format .= $next - $prev * $ary . $units[$i]; } $prev = $next; } return $format;}//簡單點的print_r(format_every(12345678));//1234金56銀78銅//假如1坨=100金,則:print_r(format_every(12345678,100,array('銅', '銀', '金','坨')));//12坨34金56銀78銅//位元組換算print_r(format_every(123456789,1024,array('B', 'KB', 'MB', 'GB', 'TB', 'PB')));//117MB755KB277B
function exchange($copper){ $gold = (int) ($copper / 10000); $silver = (int) ($copper / 100 - $gold * 100); $copper = $copper % 100; return array($gold, $silver, $copper);}
簡單做。從額數最大的金開始處理,先整除,再模除,金銀銅依次處理。輸出的時候判斷再做個判斷,代碼如下:
0) { $result .= $gold ."金"; } if($sliver > 0) { $result .= $sliver ."銀"; } if($cu > 0) { $result .= $cu ."銅"; } return $result; } //test echo level(102135); echo ""; echo level(1544); echo ""; echo level(99);
function level($money){ $ag = floor($money /100); $cu = $money % 100; $golden = floor($ag / 100); $ag = $ag % 100; echo "{$golden}金{$ag}銀{$cu}銅幣";}
很簡單的寫了一個。
def make_change(money, coins) dp = [0] path = [] result = {} coins.each_with_index do |coin, index| coin.upto(money) do |i| if !dp[i - coin].nil? && (dp[i].nil? || dp[i - coin] + 1 < dp[i]) dp[i] = dp[i - coin] + 1 coins[index] += 1 path[i] = i - coin end end end if path[money].nil? puts "impossible." and return end i = money loop do break if path[i].nil? result[i - path[i]] ||= 0 result[i - path[i]] += 1 i = path[i] end p result # 具體解endmake_change(102135, [10000, 100, 1])# => {1=>35, 100=>21, 10000=>10}
嗯...不知道計算速度快 還是字串截取速度快
結果: 10金幣21銅幣35銀幣
function change($number){
static $jin; static $yin; static $ton; if($number >= pow(10,4)){ $jin = intval($number/pow(10,4)); change($number -$jin*pow(10,4)); }else if($number >= pow(10,2)){ $yin = intval($number/pow(10,2)); change($number-$yin*pow(10,2)); }else{ $ton = $number; } return array($jin,$yin,$ton);}$number = 10110245;print_r(change($number));
/** * @param $coins int 幣數 * @return string 格式化資訊 */function coinFormatter($coins){ $coins = intval($coins); $jin = intval($coins/10000); $yin = intval($coins/100 - $jin*100); $tong = $coins%100; $info = ''; if($jin>0) { $info = $jin . "金"; } if($yin>0){ $info = $info.$yin."銀"; } if($tong >0){ $info = $info.$tong."銅"; } return $info;}echo coinFormatter(114523);echo "\n";echo coinFormatter(523);echo "\n";echo coinFormatter(3);/*輸出結果:11金45銀23銅5銀23銅3銅*/
關注公眾號php技術大全:phpgod,精彩分享每日不斷。