zoukankan      html  css  js  c++  java
  • 405. 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 //        每次取出最右边四位,如果其大于等于10,找到对应的字母加入结果,反之则将对应的数字加入结果,然后num像右平移四位,
     3 //        循环停止的条件是num为0,或者是已经循环了7次(java中int是32位,移了7次以后只剩4位了)
     4         String res = "", str = "0123456789abcdef";
     5         int cnt = 0;
     6         while (num != 0 && cnt++ < 8) {
     7             res = str.charAt((num & 0xf)) + res;
     8             num >>= 4;
     9         }
    10         return res.isEmpty() ? "0" : res;  
    11     }
  • 相关阅读:
    数据库高级链表查询,重点可以多看看
    数据库多表查询,一对一关系,一对多关系,多对多关系
    Django基础
    前端之JavaScript
    前端之Jquery
    CF888E Maximum Subsequence-折半搜索
    HNOI2010 平面图判定
    CEOI 2011Traffic
    LuoguP1710 地铁涨价
    Luogu2059 卡牌游戏-概率DP
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7727785.html
Copyright © 2011-2022 走看看