返回介绍

solution / 0400-0499 / 0405.Convert a Number to Hexadecimal / README_EN

发布于 2024-06-17 01:04:01 字数 3517 浏览 0 评论 0 收藏 0

405. Convert a Number to Hexadecimal

中文文档

Description

Given an integer num, return _a string representing its hexadecimal representation_. For negative integers, two’s complement method is used.

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

Note: You are not allowed to use any built-in library method to directly solve this problem.

 

Example 1:

Input: num = 26
Output: "1a"

Example 2:

Input: num = -1
Output: "ffffffff"

 

Constraints:

  • -231 <= num <= 231 - 1

Solutions

Solution 1

class Solution:
  def toHex(self, num: int) -> str:
    if num == 0:
      return '0'
    chars = '0123456789abcdef'
    s = []
    for i in range(7, -1, -1):
      x = (num >> (4 * i)) & 0xF
      if s or x != 0:
        s.append(chars[x])
    return ''.join(s)
class Solution {
  public String toHex(int num) {
    if (num == 0) {
      return "0";
    }
    StringBuilder sb = new StringBuilder();
    while (num != 0) {
      int x = num & 15;
      if (x < 10) {
        sb.append(x);
      } else {
        sb.append((char) (x - 10 + 'a'));
      }
      num >>>= 4;
    }
    return sb.reverse().toString();
  }
}
class Solution {
public:
  string toHex(int num) {
    if (num == 0) return "0";
    string s = "";
    for (int i = 7; i >= 0; --i) {
      int x = (num >> (4 * i)) & 0xf;
      if (s.size() > 0 || x != 0) {
        char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a');
        s += c;
      }
    }
    return s;
  }
};
func toHex(num int) string {
  if num == 0 {
    return "0"
  }
  sb := &strings.Builder{}
  for i := 7; i >= 0; i-- {
    x := num >> (4 * i) & 0xf
    if x > 0 || sb.Len() > 0 {
      var c byte
      if x < 10 {
        c = '0' + byte(x)
      } else {
        c = 'a' + byte(x-10)
      }
      sb.WriteByte(c)
    }
  }
  return sb.String()
}

Solution 2

class Solution {
  public String toHex(int num) {
    if (num == 0) {
      return "0";
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 7; i >= 0; --i) {
      int x = (num >> (4 * i)) & 0xf;
      if (sb.length() > 0 || x != 0) {
        char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a');
        sb.append(c);
      }
    }
    return sb.toString();
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文