405. Convert a Number to Hexadecimal

Easy

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"
package leetcode.easy;

public class ConvertANumberToHexadecimal {
char[] map = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; @org.junit.Test
public void test() {
System.out.println(toHex(26));
System.out.println(toHex(-1));
} public String toHex(int num) {
if (num == 0) {
return "0";
}
String result = "";
while (num != 0) {
result = map[(num & 15)] + result;
num = (num >>> 4);
}
return result;
}
}

最新文章

  1. 我心目中的Asp.net核心对象
  2. INSTALLMENT of QValue
  3. servlet学习笔记二
  4. ORACLE 基础知识积累
  5. JS类库函数收集中....
  6. uva 10054 The Necklac(欧拉回路)
  7. 【转】How to view word document in WPF application
  8. ExtJs Tree加载选项卡,选项卡加载页面不用iframe
  9. 部分PC端安卓管理器使用强行断开重连的方法来连接手机,容易丢书数据,损坏数据
  10. 低功耗蓝牙BLE外围模式(peripheral)-使用BLE作为服务端
  11. VS发布网站步骤(先在vs上发布网站到新的文件夹,然后挂到iis上面)
  12. JS中window.showModalDialog()详解(转)
  13. typescript入门基础
  14. 为什么我不推荐你使用vue-cli创建脚手架?
  15. python __init__() 和__new__()简析
  16. Tomcat 8005/8009/8080/8443端口的作用
  17. 过滤选择器first与子元素过滤选择器first-child的区别
  18. Python Selenium 文件上传之SendKeys
  19. Flex4学习笔记1---基本语法
  20. JUC——线程同步辅助工具类(Exchanger,CompletableFuture)

热门文章

  1. centos安装zookeeper,并集群配置
  2. ThreadLocal源码原理以及防止内存泄露
  3. Kotlin协程第一个示例剖析及Kotlin线程使用技巧
  4. 微信小程序~模板template引用
  5. 注解@Transient
  6. PHP隐藏IP地址末位的方法
  7. onreadystatechange和onload区别分析
  8. HDU - 3311: Dig The Wells (斯坦纳树)
  9. nginx1.15.10配置使用非https访问返回403
  10. 《团队作业第三、第四周》五阿哥团队作业--Scrum 冲刺阶段--Day1--领航