zoukankan      html  css  js  c++  java
  • [leetcode] Convert a Number to Hexadecimal

    Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

    Note:

    1. All letters in hexadecimal (a-f) must be in lowercase.
    2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
    3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
    4. You must not use any method provided by the library which converts/formats the number to hex directly.

    Example 1:

    Input:
    26
    
    Output:
    "1a"
    

    Example 2:

    Input:
    -1
    
    Output:
    "ffffffff"
    

    分析:题目翻译一下:要求把十进制数转变成十六进制数。

    对于正数,很好处理,对正数不断的除以16,将余数不断的加到结果中就可以了。代码如下:

     1 public String toHex(int num) {
     2         if ( num == 0 ) return "0";
     3         StringBuffer res = new StringBuffer();
     4         Map<Integer,Character> map = new HashMap<>();
     5         map.put(10,'a');
     6         map.put(11,'b');
     7         map.put(12,'c');
     8         map.put(13,'d');
     9         map.put(14,'e');
    10         map.put(15,'f');
    11         if ( num > 0 ){
    12             while ( num > 0 ){
    13                 int t = num % 16;
    14                 if ( t >= 10 ) res.append(map.get(t));
    15                 else res.append(t);
    16                 num /= 16;
    17             }
    18         }
    19         return res.reverse().toString();
    20     }

    但是这个方法只能处理正数。对于负数,首先我们来分析一下,负数存储的的方式是补码,比如-5:

    5的原码:00000000 00000000 00000000 00000101

    按位取反:11111111 11111111 11111111 11111010

    末位 + 1 = 11111111 11111111 11111111 11111010 + 1 = 11111111 11111111 11111111 11111011

    也就是负数的存储方式是按位取反,末位加一。

    对于取反,比如~5 = -5-1,即~x = -x - 1。

    思考了一下,这条路不太能走得通,因为我们相当于要拿到11111111 11111111 11111111 11111011对应的无符号整数的值,不太好搞。

    思路二:因为无论什么类型的数字,存在内存里都是以二进制存的,那么我们是否可以从根本上实现转换呢?

    16进制是每四位一个数出来,那么就按照四位生成一个。

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

      注意这里的关键;>>>代表无符号右移,忽略符号位。

  • 相关阅读:
    转: sublime text常用插件和快捷键
    转: markdown基本语法
    sqlite详细介绍
    webpack配置babel-loader
    vue骨架屏以及seo优化
    路由滚动行为
    anywhere随启随用的静态文件服务器
    node.js http-server 搭建本地服务器
    vuex中mutations数据响应
    vue项目开发优化
  • 原文地址:https://www.cnblogs.com/boris1221/p/9800180.html
Copyright © 2011-2022 走看看