【LeetCode】1017. Convert to Base -2(十进制转换为负整数进制)
题目
Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two).
The returned string must have no leading zeroes, unless the string is “0”.
Example 1:
Input: 2
Output: "110"
Explantion: (-2) ^ 2 + (-2) ^ 1 = 2
Example 2:
Input: 3
Output: "111"
Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
Example 3:
Input: 4
Output: "100"
Explantion: (-2) ^ 2 = 4
Note:
0 <= N <= 10^9
题意
这题就是要将一个10进制数转换成 -2 进制数。
思路
对于将 10 进制转换为 - N 进制(N为正整数)的题,可以采用如下方法:
// 将十进制整数i转换为 -N 进制(N为正整数)
string baseNegN(int i, int N) {
vector<int>remainder; // 用来存余数
string res = ""; // 存储最终结果
remainder.clear();
int j = i, k;
while(j != 0) {
if(j > 0) {
remainder.push_back(j % (-N));
j = j / (-N);
} else if(j == 0) {
remainder.push_back(0);
j = j / (-N);
} else {
k = j / (-N) + 1; // 因为j/(-N)*(-N)比j大,所以要加1
remainder.push_back(j - k * (-N));
j = k;
}
}
for(j=0; j<remainder.size(); ++j) {
ans.append(1, remainder[j]);
}
}
代码
class Solution {
public:
string baseNeg2(int N) {
if(N == 0) return "0";
vector<int>v;
int i, j, k;
v.clear();
i = N;
while(i != 0) {
if(i > 0) {
v.push_back(i % (-2));
i = i / (-2);
} else {
if(i % (-2) == 0) {
i = i / (-2);
v.push_back(0);
} else {
j = i / (-2) + 1;
v.push_back(i - j * (-2));
i = j;
}
}
}
string ans = "";
for(i=v.size()-1; i>=0; --i) {
ans.append(1, v[i]+'0');
}
return ans;
}
};