Skip to content

1256. Encode Number 👎

  • Time: $O(\log\texttt{num})$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  string encode(int num) {
    string binaryStr = bitset<30>(num + 1).to_string();
    binaryStr.erase(0, binaryStr.find_first_not_of('0'));
    return binaryStr.substr(1);
  }
};
1
2
3
4
5
class Solution {
  public String encode(int num) {
    return Integer.toBinaryString(num + 1).substring(1);
  }
}
1
2
3
class Solution:
  def encode(self, num: int) -> str:
    return bin(num + 1)[3:]