[LeetCode] Encode Number

1256. Encode Number

Given a non-negative integer num, Return its encoding string.

The encoding is done by converting the integer to a string using a secret function that you should deduce from the following table:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
string encode(int num) {
if(num == 0) return "";
int now = 2;
string res = "0";
while(num > now) {
num -= now;
now *= 2;
res.push_back('0');
}
num -= 1;
int p = res.length() - 1;
while(num) {
if(num & 1) res[p] = '1';
num /= 2;
p--;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/24/PS/LeetCode/encode-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.