LeetCode 1017 负二进制转换【二进制】HERODING的LeetCode之路

在这里插入图片描述

解题思路:
照理说进制转换作为最基础的算法,应该是不需要专门开一个专题去讲解的,但是在接触到这道题时,一时间让我头脑发懵。因为常规的进制转换都是正整数进制转换,还没有遇见过负数进制,正常的求解过程一般是这样,假设x进制,十进制数为n,代码如下:

...
while(n) {
    
    
    res += n % x;
    n /= x;
}
return res;
...

但是在负数情况下,取余会带有负号,那其实求x的绝对值的余数就能解决这个问题,但是之后又会遇到新的问题,直接通过除以x的方式进行移位操作会出现问题,所以需要分类讨论:

class Solution {
    
    
public:
    string baseNeg2(int n) {
    
    
        if(n == 0) {
    
    
            return "0";
        }
        string res;
        while(n != 0) {
    
    
            if(n % 2 == 0) {
    
    
                res += '0';
            } else {
    
    
                res += '1';
            }
            if(n > 0) n /= -2;
            else n = (n - 1) / (-2);
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

但是这样的方式不好理解,每次翻转为负数之后需要-1,这是因为负二进制的第一位的数值一定是正数,要把后面的负数求和抵消,所以必须得翻转为正数。但是如果换一种操作,那么就很好理解了,代码如下:

class Solution {
    
    
public:
    string baseNeg2(int n) {
    
    
        if(n == 0) {
    
    
            return "0";
        }
        string res;
        while(n) {
    
    
            int r = n & 1;
            res += to_string(r);
            n = (n - r) / -2;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

在位移前,把最后一位上的数减去,即清零,然后再移位,这是最标准的做法。

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/129971948