The encoding is the binary representation of num + 1, but with the leading ‘1’ removed. This is because the encoding table matches the binary numbers from 1 upwards, skipping the leading bit.
classSolution {
public String encode(int num) {
if (num == 0) return"";
StringBuilder ans =new StringBuilder();
num++;
while (num > 1) {
ans.insert(0, num & 1);
num >>= 1;
}
return ans.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funencode(num: Int): String {
if (num ==0) return""var n = num + 1val ans = StringBuilder()
while (n > 1) {
ans.insert(0, n and 1)
n = n shr 1 }
return ans.toString()
}
}
1
2
3
4
5
6
classSolution:
defencode(self, num: int) -> str:
if num ==0:
return"" b = bin(num +1)[3:]
return b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnencode(num: i32) -> String {
if num ==0 {
return String::new();
}
letmut n = (num +1) asu32;
letmut ans = String::new();
while n >1 {
ans.insert(0, char::from(b'0'+ (n &1) asu8));
n >>=1;
}
ans
}
}