zoukankan      html  css  js  c++  java
  • 405.十进制转换成十六进制(考虑负数情况) Convert a Number to Hexadecimal

    十进制转二进制
    1. static void Main(string[] args) {
    2. int i = 60;
    3. string s = "";
    4. while (i>0) {
    5. s = (i % 2).ToString() + s;
    6. i /= 2;
    7. }
    8. Console.WriteLine(Convert.ToString(60, 2));//c#转换方法
    9. Console.WriteLine(s);
    10. }


    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"
    

    Subscribe to see which companies asked this question

    对于负数,先进行预处理,位取反后加1 

    1. public class Solution {
    2. public string ToHex(int num) {
    3. if (num == 0)
    4. {
    5. return "0";
    6. }
    7. long number = Convert.ToInt64(num);
    8. if (number < 0)
    9. {
    10. number = UInt32.MaxValue + number + 1;//取反+1
    11. }
    12. char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    13. string hexString = "";
    14. long n = 0;
    15. char c = ' ';
    16. while (number > 0)
    17. {
    18. n = number % 16;
    19. c = hex[n];
    20. hexString = c + hexString;
    21. number /= 16;
    22. }
    23. return hexString;
    24. }
    25. }





  • 相关阅读:
    软工作业01 P18 第四题
    自我介绍
    进行代码复审训练
    源代码管理工具调查
    软工作业PSP与单元测试训练
    进行代码复审训练
    源代码管理工具
    软工作业PSP与单元测试训练
    作业
    第一堂课
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/4ed044d7622df0ceeddb2a291ca8d073.html
Copyright © 2011-2022 走看看