php版本 N進位演算法

來源:互聯網
上載者:User

 

 

基礎一演算法:

這個演算法能夠在2~9進位之間與10進位進行轉換。

因為使用遞迴的方式,在進行10進位=>N進位的轉換過程中需要提供一個數組作為引用變數。儲存轉換的結果

 

<?php<br />/**<br /> * 十進位轉為N進位<br /> *<br /> * @param int $ix 待轉換的10進位數<br /> * @param int $im 進位2-9之間的數字<br /> * @param array $aBuf<br /> * @return void<br /> */<br />function k($ix, $im, & $aBuf)<br />{<br /> if ($ix > $im)<br /> k(floor($ix/$im), $im, $aBuf);<br /> elseif($ix == $im)<br /> $aBuf[] = '1';<br /> $aBuf[] = $ix % $im;<br />}<br />/**<br /> * N進位制轉為十進<br /> *<br /> * @param string $sS 待轉換的N進位數字串<br /> * @param int $im 進位2-9之間的數字<br /> * @return int<br /> */<br />function rk($sS, $im)<br />{<br /> $iLen = strlen($sS)-1;<br /> for ($i=$iLen; $i>=0; $i--)<br /> $iBuf += pow($im, $i) * intval($sS{abs($i - $iLen)});<br /> return $iBuf;<br />}<br />$aBuf = array();<br />$iNHex = 2;//進位數 2-9 之間的數字<br />$iSource = 129;//待轉換的10進位數<br />echo "前提:2 ≤ N ≥ 9,當前為". $iNHex ."進位結果;/n";<br />k($iSource, $iNHex, $aBuf);<br />echo '10進位->N進位:'.join('', $aBuf) ."/n";<br />echo 'N進位->10進位:'.rk(join('', $aBuf), $iNHex);<br />?> 

 

如要使用,請標明出處,謝謝。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.