Encode Number

medium bit manipulation math binary

Problem

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: 0 maps to "", 1 to "0", 2 to "1", 3 to "00", 4 to "01", 5 to "10", 6 to "11", 7 to "000", and so on.

Inputnum = 5
Output"10"
num + 1 = 6, whose binary is 110. Dropping the leading 1 leaves "10".

def encode(num):
    m = num + 1
    bits = bin(m)[2:]
    return bits[1:]
function encode(num) {
  const m = num + 1;
  const bits = m.toString(2);
  return bits.slice(1);
}
class Solution {
    public String encode(int num) {
        int m = num + 1;
        String bits = Integer.toBinaryString(m);
        return bits.substring(1);
    }
}
string encode(int num) {
    int m = num + 1;
    string bits = "";
    while (m > 0) { bits = char('0' + (m & 1)) + bits; m >>= 1; }
    return bits.substr(1);
}
Time: O(log n) Space: O(log n)