首页 > 其他分享 >leetcode-405-easy

leetcode-405-easy

时间:2023-01-22 20:11:46浏览次数:39  
标签:10 return String 405 num easy Input sb leetcode

Convert a Number to Hexadecimal

Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

Note: You are not allowed to use any built-in library method to directly solve this problem.

Example 1:

Input: num = 26
Output: "1a"
Example 2:

Input: num = -1
Output: "ffffffff"
Constraints:

-231 <= num <= 231 - 1

思路一:先把整数当成二进制,每4个 bit 位就是一个16进制字符,循环取整数低位的4个 bit 位,可以计算得到16进制。看了一下题解,补码的操作是不用的

    public String toHex(int num) {
        if (num == 0) {
            return "0";
        }

        //不用处理
    //    if (num < 0) {
    //        num = -num - 1;
    //        num ^= 0xffffffff;
    //    }

        String[] values = {"a", "b", "c", "d", "e", "f"};

        StringBuilder sb = new StringBuilder();
        while (num != 0) {
            int x = num & 0b1111;
            num >>>= 4;

            if (x >= 10) {
                sb.insert(0, values[x - 10]);
            } else {
                sb.insert(0, x);
            }
        }

        return sb.toString();
    }

标签:10,return,String,405,num,easy,Input,sb,leetcode
From: https://www.cnblogs.com/iyiluo/p/17064613.html

相关文章

  • leetcode-501-easy
    FindModeinBinarySearchTreeGiventherootofabinarysearchtree(BST)withduplicates,returnallthemode(s)(i.e.,themostfrequentlyoccurredelemen......
  • leetocde-374-easy
    GuessNumberHigherorLowerWeareplayingtheGuessGame.Thegameisasfollows:Ipickanumberfrom1ton.YouhavetoguesswhichnumberIpicked.Eve......
  • LeetCode最长回文子串(/dp)
    原题解题目约束解法解法一#include<iostream>#include<string>#include<vector>usingnamespacestd;classSolution{public:stringlongestPa......
  • LeetCode_单周赛_329
    2544.交替数字和代码1转成字符串,逐个判断classSolution{publicintalternateDigitSum(intn){char[]s=(""+n).toCharArray();intt......
  • 【队列】LeetCode 281. 锯齿迭代器
    题目链接281.锯齿迭代器思路使用队列进行保存代码publicclassZigzagIterator{Queue<Iterator<Integer>>queue=newLinkedList<>();publicZigzagIt......
  • 【队列】LeetCode 346. 数据流中的移动平均值
    题目链接346.数据流中的移动平均值思路队列设计基础题代码classMovingAverage{privateIntegercurrentSum=0;privateQueue<Integer>queue=newLi......
  • [LeetCode] 684. Redundant Connection
    Inthisproblem,atreeisan undirectedgraph thatisconnectedandhasnocycles.Youaregivenagraphthatstartedasatreewith n nodeslabeledfrom......
  • leetcode笔记——328周赛
    1.二维前缀和,二维差分304.二维区域和检索-矩阵不可变-力扣(LeetCode)二维前缀和怎么处理,注意加减的下标 2.2537.统计好子数组的数目-力扣(LeetCode)首先看到子数......
  • 【双指针】LeetCode 409. 最长回文串
    题目链接409.最长回文串思路遍历字符串过程中统计字符出现个数,如果达到2则说明可以放到回文串的两端,需要result+=2。遍历完之后的回文串如果长度小于s,说明s中存......
  • LeetCode.541 反转字符串II
    1.题目给定一个字符串s和一个整数k,从字符串开头算起,每计数至2k个字符,就反转这2k字符中的前k个字符。如果剩余字符少于k个,则将剩余字符全部反转。如果剩余字符小......