Convert a Number to Hexadecimal

2023-12-27 04:58
文章标签 number convert hexadecimal

本文主要是介绍Convert a Number to Hexadecimal,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

题目地址: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:

  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:
26Output:
"1a"

Example 2:

Input:
-1Output:
"ffffffff"

题目是将十进制转换为十六进制,整数还是比较好处理的,但是这个题目的关键是负数,要理解负数在计算机中是如何表示的:

public class ConvertANumberToHexadecimal {public static final String[] digit= {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};public String toHex(int num) {StringBuilder reslut = new StringBuilder("");if (num > 0) {while (num != 0) {reslut.insert(0, digit[num % 16]);num /= 16;}} else if (num == 0){reslut.insert(0, "0");} else {// 以下是截取十六进制每位对应的二进制数值// 15 to binnary: 0000 0000 0000 0000 0000 0000 0000 1111reslut.insert(0, digit[num & 15]);// 240 to binnary: 0000 0000 0000 0000 0000 0000 1111 0000reslut.insert(0, digit[(num & 240) >> 4]);// 3840 to binnary: 0000 0000 0000 0000 0000 1111 0000 0000reslut.insert(0, digit[(num & 3840) >> 8]);// 61440 to binnary: 0000 0000 0000 0000 1111 0000 0000 0000reslut.insert(0, digit[(num & 61440) >> 12]);// 983040 to binnary: 0000 0000 0000 1111 0000 0000 0000 0000reslut.insert(0, digit[(num & 983040) >> 16]);// 15728640 to binnary: 0000 0000 1111 0000 0000 0000 0000 0000reslut.insert(0, digit[(num & 15728640) >> 20]);// 251658240 to binnary: 0000 1111 0000 0000 0000 0000 0000 0000reslut.insert(0, digit[(num & 251658240) >> 24]);// 1879048192 to binnary: 0111 0000 0000 0000 0000 0000 0000 0000reslut.insert(0, digit[((num & 1879048192) >> 28) + 8]);}return reslut.toString();}public static void main(String[] args) {ConvertANumberToHexadecimal hexadecimal = new ConvertANumberToHexadecimal();System.out.println(hexadecimal.toHex(-13));}
}

其实在JDK中已经封装好了十进制转十六进制的方法,它是这么写的:

Integer.toHexString(int i)

那么我们看一下JDK是怎么实现的:

/*** Returns a string representation of the integer argument as an* unsigned integer in base&nbsp;16.** <p>The unsigned integer value is the argument plus 2<sup>32</sup>* if the argument is negative; otherwise, it is equal to the* argument.  This value is converted to a string of ASCII digits* in hexadecimal (base&nbsp;16) with no extra leading* {@code 0}s.** <p>The value of the argument can be recovered from the returned* string {@code s} by calling {@link* Integer#parseUnsignedInt(String, int)* Integer.parseUnsignedInt(s, 16)}.** <p>If the unsigned magnitude is zero, it is represented by a* single zero character {@code '0'} ({@code '\u005Cu0030'});* otherwise, the first character of the representation of the* unsigned magnitude will not be the zero character. The* following characters are used as hexadecimal digits:** <blockquote>*  {@code 0123456789abcdef}* </blockquote>** These are the characters {@code '\u005Cu0030'} through* {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through* {@code '\u005Cu0066'}. If uppercase letters are* desired, the {@link java.lang.String#toUpperCase()} method may* be called on the result:** <blockquote>*  {@code Integer.toHexString(n).toUpperCase()}* </blockquote>** @param   i   an integer to be converted to a string.* @return  the string representation of the unsigned integer value*          represented by the argument in hexadecimal (base&nbsp;16).* @see #parseUnsignedInt(String, int)* @see #toUnsignedString(int, int)* @since   JDK1.0.2*/
public static String toHexString(int i) {
    return toUnsignedString0(i, 4);
}

然后再看下toUnsignedString0及其内部所涉及到的方法的实现:

/*** Convert the integer to an unsigned number.*/
private static String toUnsignedString0(int val, int shift) {// assert shift > 0 && shift <=5 : "Illegal shift value";int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);int chars = Math.max(((mag + (shift - 1)) / shift), 1);char[] buf = new char[chars];formatUnsignedInt(val, shift, buf, 0, chars);// Use special constructor which takes over "buf".return new String(buf, true);
}/*** Returns the number of zero bits preceding the highest-order* ("leftmost") one-bit in the two's complement binary representation* of the specified {@code int} value.  Returns 32 if the* specified value has no one-bits in its two's complement representation,* in other words if it is equal to zero.** <p>Note that this method is closely related to the logarithm base 2.* For all positive {@code int} values x:* <ul>* <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}* <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}* </ul>** @param i the value whose number of leading zeros is to be computed* @return the number of zero bits preceding the highest-order*     ("leftmost") one-bit in the two's complement binary representation*     of the specified {@code int} value, or 32 if the value*     is equal to zero.* @since 1.5*/
public static int numberOfLeadingZeros(int i) {// HD, Figure 5-6if (i == 0)return 32;int n = 1;if (i >>> 16 == 0) { n += 16; i <<= 16; }if (i >>> 24 == 0) { n +=  8; i <<=  8; }if (i >>> 28 == 0) { n +=  4; i <<=  4; }if (i >>> 30 == 0) { n +=  2; i <<=  2; }n -= i >>> 31;return n;
}/*** Format a long (treated as unsigned) into a character buffer.* @param val the unsigned int to format* @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)* @param buf the character buffer to write to* @param offset the offset in the destination buffer to start at* @param len the number of characters to write* @return the lowest character  location used*/static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {int charPos = len;int radix = 1 << shift;int mask = radix - 1;do {buf[offset + --charPos] = Integer.digits[val & mask];val >>>= shift;} while (val != 0 && charPos > 0);return charPos;
}/*
* Package private constructor which shares value array for speed.
* this constructor is always expected to be called with share==true.
* a separate constructor is needed because we already have a public
* String(char[]) constructor that makes a copy of the given char[].
*/
String(char[] value, boolean share) {// assert share : "unshared not supported";this.value = value;
}

这篇关于Convert a Number to Hexadecimal的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/541938

相关文章

usaco 1.2 Name That Number(数字字母转化)

巧妙的利用code[b[0]-'A'] 将字符ABC...Z转换为数字 需要注意的是重新开一个数组 c [ ] 存储字符串 应人为的在末尾附上 ‘ \ 0 ’ 详见代码: /*ID: who jayLANG: C++TASK: namenum*/#include<stdio.h>#include<string.h>int main(){FILE *fin = fopen (

题目1380:lucky number

题目1380:lucky number 时间限制:3 秒 内存限制:3 兆 特殊判题:否 提交:2839 解决:300 题目描述: 每个人有自己的lucky number,小A也一样。不过他的lucky number定义不一样。他认为一个序列中某些数出现的次数为n的话,都是他的lucky number。但是,现在这个序列很大,他无法快速找到所有lucky number。既然

Jenkins 通过 Version Number Plugin 自动生成和管理构建的版本号

步骤 1:安装 Version Number Plugin 登录 Jenkins 的管理界面。进入 “Manage Jenkins” -> “Manage Plugins”。在 “Available” 选项卡中搜索 “Version Number Plugin”。选中并安装插件,完成后可能需要重启 Jenkins。 步骤 2:配置版本号生成 打开项目配置页面。在下方找到 “Build Env

【Hdu】Minimum Inversion Number(逆序,线段树)

利用线段树在nlogn的时间复杂度内求一段数的逆序。 由于给的序列是由0 ~ n -1组成的,求出初始的逆序之后可以递推出移动之后的逆序数。 #include<cstdio>#include<iostream>#include<cstring>#include<algorithm>using namespace std;typedef long long LL;const in

【JavaScript】基本数据类型与引用数据类型区别(及为什么String、Boolean、Number基本数据类型会有属性和方法?)

基本数据类型   JavaScript基本数据类型包括:undefined、null、number、boolean、string。基本数据类型是按值访问的,就是说我们可以操作保存在变量中的实际的值。 1)基本数据类型的值是不可变的 任何方法都无法改变一个基本类型的值,比如一个字符串: var name = "change";name.substr();//hangconsole.log

ORA-24067: exceeded maximum number of subscribers for queue ADMIN.SMS_MT_QUEUE

临时处理办法: delete from aq$_ss_MT_tab_D;delete from aq$_ss_MT_tab_g;delete from aq$_ss_MT_tab_h;delete from aq$_ss_MT_tab_i;delete from aq$_ss_MT_tab_p;delete from aq$_ss_MT_tab_s;delete from aq$

org.springframework.core.convert.ConversionFailedException

适用: 1.你在springmvc.xml中写了静态资源处理<mvc:resources location="/" mapping="/**"></mvc:resources> 2.你在springmvc.xml中写了日期类型转换 解决方法: 首先检测你的spring版本,然后 1.spring3.0后将<mvc:resources location="/" mapping="/**">

SQLSERVER排名函数RANK,DENSE_RANK,NTILE,ROW_NUMBER

SQL SERVER排名函数RANK,DENSE_RANK,NTILE,ROW_NUMBER 前言 本文意于用实例数据帮助理解SQL SERVER排名函数RANK,DENSE_RANK,NTILE,ROW_NUMBER。 准备工作 创建测试表:   ? 1 2 3 4 5 create table test( id int identity(1,1)

[LeetCode] 137. Single Number II

题:https://leetcode.com/problems/single-number-ii/ 题目大意 给定array,其中有一个元素只出现了1次,其他元素都出现了3次。 思路 求和 减去 (set(array)*3 - array)/2 作为答案。 class Solution {public int singleNumber(int[] nums) {Set<Long> se

Oracle - ORA-01789: Query block has incorrect number of result columns

一、原因     这个错误一般是在执行表之间的相加(union),相减(minus)等SQL语句时,两个个查询块具有不一致的结果列数所导致的。 二、方案     只要将两段SQL语句的列数调整为一致就可以解决。使用union时,要注意数据库字段的格式要一致,如varchar和nvarchar是不一样的。