日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode】405 Convert a Number to Hexadecimal (java实现)

發布時間:2024/4/17 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode】405 Convert a Number to Hexadecimal (java实现) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

原題鏈接

https://leetcode.com/problems/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:

  • All letters in hexadecimal (a-f) must be in lowercase.
  • 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.
  • The given number is guaranteed to fit within the range of a 32-bit signed integer.
  • You must not use any method provided by the library which converts/formats the number to hex directly.
  • Example 1:

    Input: 26Output: "1a"

    Example 2:

    Input: -1Output: "ffffffff"

    題目要求

    題目叫“將數字轉化為十六進制”,顧名思義,這里需要注意的是數字是包含負數的,所以如果方法不很合適,處理起來會稍微麻煩一些。
    要求:

  • 轉化后的十六進制字符串都是小寫的;
  • 十六進制字符串不能以0開頭(如果只有一個0除外);
  • 數字大小在32bit范圍內,不用擔心處理數據時溢出;
  • 不能使用庫里的轉化和格式打印;
  • 解法

    解法一:最原始的方法,完全按照數字的源碼、反碼、補碼的格式來轉化,這種思路下,就要先將數字轉化為2進制,再將二進制轉化為十六進制。同時,還需要注意數字為負數時,需要一些特殊的操作。這種解法非常麻煩,但是卻非常直接。

    public String toHex(int num) {if (num == 0) {return "0";}int MAX = 32;boolean isNegative = false;int bits[] = new int[MAX];if (num < 0) {isNegative = true;bits[MAX - 1] = 1;num = -num;}int i = 0;// 轉化為二進制的原碼while (num > 0) {bits[i++] = num % 2;num /= 2;}// 如果是負數,需要取反并且+1從而得到補碼if (isNegative) {// 取反for (int j = 0; j < bits.length - 1; j++) {bits[j] = (bits[j] + 1) % 2;}// +1int digit = 1;int res = 0;for (int j = 0; j < bits.length - 1; j++) {res = bits[j] + digit;bits[j] = res % 2;digit = res / 2;}}// 二進制轉化為十六進制String ret = "";for (int j = 0; j < bits.length; j += 4) {int data = 0;for (int j2 = 0; j2 < 4; j2++) {data += bits[j + j2] * (1 << j2);}ret = String.format("%x", data) + ret;}// 去掉字符串前面多余的0for (int j = 0; j < ret.length(); j++) {if (ret.charAt(j) != '0') {ret = ret.substring(j);break;}}return ret; }

    解法二:第二種解法就是按位與來獲取。既然是得到十六進制,那么每次與上0xF(二進制就是1111),得到一個值,然后數字向右移動4位,這里需要注意的是數字是有符號的,剛好可以利用Java提供的無符號移動>>>。完美!!!

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

    轉載于:https://my.oschina.net/styshoo/blog/780869

    總結

    以上是生活随笔為你收集整理的【LeetCode】405 Convert a Number to Hexadecimal (java实现)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。