-2进制转换
string baseNeg2(int N) {
// 不能用%-2操作,因为需要余数为正
string ans;
while (N) {
int rem = N & 1;
ans = to_string(rem) + ans;
N = -(N >> 1);
}
return !ans.empty() ? ans : "0";
}
删除9
Start from integer 1, remove any integer that contains 9 such as 9, 19, 29...
So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...
Given a positive integer
n, you need to return the n-th integer after removing. Note that 1 will be the first integer.Example 1:
Input: 9 Output: 10Hint: n will not exceed
9 x 10^8.
int newInteger(int n) {
// 删除9后的数正好就是九进制数,这题就是把十进制转成九进制
// 扩展:如果删除7,还是九进制,只是结果需映射7=>8,8=>9。
int ans = 0, base = 1;
while (n) {
ans += (n % 9) * base; // 从后往前拼上
n /= 9;
base *= 10;
}
return ans;
}
相似的RGB颜色
string similarRGB(string color) {
return "#" + similarColor(color.substr(1, 2))
+ similarColor(color.substr(3, 2))
+ similarColor(color.substr(5, 2));
}
string similarColor(const string &ab) {
const string mapping = "0123456789abcdef";
// #ab要变成#xx,#xx=16*x+x=17x,所以要找最接近#ab的17的倍数
int num = stoi(ab, NULL, 16);
int x = (num + 8) / 17; // "四舍五入"
return string(2, mapping[x]);
}