lihe/Leetcode

Leetcode_1256_Encode Number

Opened this issue · 0 comments

lihe commented

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:

img

Example 1:

Input: num = 23
Output: "1000"

Example 2:

Input: num = 107
Output: "101100"

Constraints:

  • 0 <= num <= 10^9

算法思路:将num+1转化为二进制后删去第一位,以字符串的格式输出。

class Solution {
public:
    string encode(int num) {
        num += 1;
        string str = "";
        while(num){
            str += to_string(num % 2);
            num /= 2;
        }
        string result  = "";
        for(int i = str.size() - 2; i > 0; i--){
            result += str[i];
        }
        return result;
    }
};