Skip to content

Latest commit

 

History

History

1256

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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:

 

Example 1:

Input: num = 23
Output: "1000"

Example 2:

Input: num = 107
Output: "101100"

 

Constraints:

  • 0 <= num <= 10^9

Companies:
Quora

Related Topics:
Math, String, Bit Manipulation

Similar Questions:

Solution 1.

The answer is the binary representation of n + 1 truncating to the least floor(log(n + 1)) significant digits.

// OJ: https://leetcode.com/problems/encode-number/
// Author: github.com/lzl124631x
// Time: O(logN)
// Space: O(logN)
class Solution {
public:
    string encode(int n) {
        ++n;
        string ans;
        int len = log(n);
        while (n) {
            ans += '0' + (n & 1);
            n >>= 1;
        }
        if (ans.size() > len) ans.pop_back();
        return string(rbegin(ans), rend(ans));
    }
};