zoukankan      html  css  js  c++  java
  • [LeetCode 405.] Convert a Number to Hexadecimal

    LeetCode 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"

    解题思路

    一道简单题,给定十进制整数,转换成十六进制表示。整数可为负数。
    除了直接调用 I/O库函数 之外,还可以直接使用位运算 —— 注意到十六进制恰好是二进制整数 4bit 一组即可得到。
    这些都没有真正涉及取余整除的操作,真正需要逐步计算的是非二的幂次为基数的进制,如 7 进制等。

    参考代码

    /*
     * @lc app=leetcode id=405 lang=cpp
     *
     * [405] Convert a Number to Hexadecimal
     */
    
    // @lc code=start
    class Solution {
    public:
    /*
        string toHex(int num) {
            char s[20];
            sprintf(s, "%x", num);
            return string(s);
        } // AC
    */
    /*
        string toHex(int num) {
            // string s;
            // ostringstream sout(s);
            // sout << hex << num;
            // return s;
            ostringstream sout;
            sout << hex << num;
            return sout.str();
        } // AC
    */
        string toHex(int num) {
            if (num == 0) return "0";
            string res;
            string maps = "0123456789abcdef";
            // while num > 0, for(;num;)
            // while num < 0, for(;i<8;)
            for(int i = 0; (i < 8) && num; i++) {
                res.push_back(maps[num & 0xF]);
                num >>= 4;
            }
            std::reverse(res.begin(), res.end());
            return res;
        } // AC, bitwise op
    };
    // @lc code=end
    
  • 相关阅读:
    C# 1.0 到 C# 3.0 委托创建过程的发展
    C#禁用窗体最大化按钮
    TeamViewer 通过Internet进行远程访问和远程支持
    c# 匿名方法
    BeginInvoke会重新开一个线程
    c# 线程调用带参数的函数
    c# msdn 委托
    判断某张表是否存在在数据库中(access 2003 与sql server 2008)
    新浪微博自动发送微博 功能已实现(net)
    validateRequest="false" 在asp.net 4.0中失效的解决办法
  • 原文地址:https://www.cnblogs.com/zhcpku/p/14361208.html
Copyright © 2011-2022 走看看