题目
https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal/
解法
- 要处理一下负数,算出反码之后再进行转换进制
- 除以 16 取整,使用了一个小技巧:
$num >>= 4;
class Solution {
private $list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
/**
* @param Integer $num
* @return String
*/
function toHex($num) {
if ($num == 0) {
return '0';
}
if ($num < 0) {
$num = 4294967296 + $num;
}
$ret = '';
while ($num > 0) {
$retNum = ($num % 16);
$num >>= 4;
$ret = $this->list[$retNum] . $ret;
}
return $ret;
}
}