405.convert-a-number-to-hexadecimal.go 461 B

1234567891011121314151617
  1. var cvt []rune = []rune{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}
  2. func toHex(num int) string {
  3. if num == 0 {
  4. return "0"
  5. }
  6. res := make([]rune, 0)
  7. // Arithmetic shifts for signed integer and logical shifts for unsigned integer.
  8. for n := uint32(num); n != 0; n >>= 4 {
  9. res = append(res, cvt[n&0xf])
  10. }
  11. for l, r := 0, len(res)-1; l < r; l, r = l+1, r-1 {
  12. res[l], res[r] = res[r], res[l]
  13. }
  14. return string(res)
  15. }