mirror of https://github.com/doocs/leetcode.git
2.3 KiB
2.3 KiB
| comments | difficulty | edit_url | rating | source | tags | |||
|---|---|---|---|---|---|---|---|---|
| true | 中等 | https://github.com/doocs/leetcode/edit/main/solution/1200-1299/1256.Encode%20Number/README.md | 1561 | 第 13 场双周赛 Q1 |
|
1256. 加密数字 🔒
题目描述
给你一个非负整数 num ,返回它的「加密字符串」。
加密的过程是把一个整数用某个未知函数进行转化,你需要从下表推测出该转化函数:

示例 1:
输入:num = 23 输出:"1000"
示例 2:
输入:num = 107 输出:"101100"
提示:
0 <= num <= 10^9
解法
方法一:位运算
我们将 num 加一,然后将其转换为二进制字符串,去掉最高位的 1 即可。
时间复杂度 O(\log n),空间复杂度 O(\log n)。其中 n 为 num 的大小。
Python3
class Solution:
def encode(self, num: int) -> str:
return bin(num + 1)[3:]
Java
class Solution {
public String encode(int num) {
return Integer.toBinaryString(num + 1).substring(1);
}
}
C++
class Solution {
public:
string encode(int num) {
bitset<32> bs(++num);
string ans = bs.to_string();
int i = 0;
while (ans[i] == '0') {
++i;
}
return ans.substr(i + 1);
}
};
Go
func encode(num int) string {
num++
s := strconv.FormatInt(int64(num), 2)
return s[1:]
}
TypeScript
function encode(num: number): string {
++num;
let s = num.toString(2);
return s.slice(1);
}