zoukankan      html  css  js  c++  java
  • [LeetCode] 405. Convert a Number to Hexadecimal

    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

    数字转换为十六进制数。

    给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。

    注意:

    十六进制中所有字母(a-f)都必须是小写。
    十六进制字符串中不能包含多余的前导零。如果要转化的数为0,那么以单个字符'0'来表示;对于其他情况,十六进制字符串中的第一个字符将不会是0字符。 
    给定的数确保在32位有符号整数范围内。
    不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这道题考察的是计算机基础。注意给定的 input 数字的范围是在 Integer 范围内,所以这里一开始我先把 input 数字转换成 long 型避免越界。之后,对于每一位的处理,也是像处理二进制数字一样。什么意思呢?如果你想知道某个十进制数字的二进制表达,在 Java 中你需要将数字的最低位和1做AND操作,并右移一位,直到这个数字为 0。转译成十六进制也是一样,但是这里我们需要一个 map,也是不断地将 num 的最低位去和 15 做 AND 操作(因为十六进制是从0到15),直到 num == 0。每次我们无符号右移 4 个位置,这是十六进制的表达。

    时间O(c) - 应该是一个常数时间,取决于最后十六进制数字的长度

    空间O(c) - 应该是一个常数时间,取决于最后十六进制数字的长度

    Java实现

     1 class Solution {
     2     char[] map = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
     3 
     4     public String toHex(int num) {
     5         // corner case
     6         if (num == 0) {
     7             return "0";
     8         }
     9 
    10         // normal case
    11         String res = "";
    12         while (num != 0) {
    13             // res = map[(num & 0xF)] + res;
    14             res = map[(num & 15)] + res;
    15             num = (num >>> 4);
    16         }
    17         return res;
    18     }
    19 }

    LeetCode 题目总结

  • 相关阅读:
    【微信小程序】后台访问-net::ERR_CONNECTION_REFUSED 及 不是request合法域名问题 的解决
    【微信小程序】引用FontAwesome字体
    【微信小程序】开发工具使用技巧(七)
    【微信小程序】小程序扩展能力(六)
    【微信小程序】小程序云开发(五)
    【微信小程序】小程序框架(四)
    javascript学习笔记
    HTML&CSS学习笔记
    mysql学习笔记
    c++ primer 笔记 (四)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/15362017.html
Copyright © 2011-2022 走看看