假设我们有一个非负整数n,我们必须找到它的编码形式。编码策略如下-
| 数 | 编码号码 |
|---|---|
0 | “” |
1 | “ 0” |
2 | “ 1” |
3 | “ 00” |
4 | “ 01” |
5 | “ 10” |
6 | “ 11” |
7 | “ 000” |
因此,如果数字为23,则结果为1000,如果数字为54,则结果为10111
为了解决这个问题,我们将遵循以下步骤-
创建一个称为bin的方法,它将取n和k,该方法的行为如下
res:=空字符串
当n> 0时
res:= res + n mod 2的数字
n:= n / 2
反转数字res
而x> res的长度
res:=用res前缀0
返回资源
实际的方法如下-
如果n = 0,则返回空字符串;如果n为1,则返回“ 0”;或者,当n为2时,则返回“ 1”
x:= log n以2为底
如果2 ^(x + 1)– 1 = n,则
ans:=空字符串
x增加1
当x不为0时,则ans:=将ans附加在0后面,并将x增加1
返回ans
返回bin(n – 2 ^ x + 1,x)
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string bin(int n, int x){
string result = "";
while(n>0){
result += (n%2) + '0';
n/=2;
}
reverse(result.begin(), result.end());
while(x>result.size())result = '0' + result;
return result;
}
string encode(int n) {
if(n == 0)return "";
if(n == 1)return "0";
if(n==2) return "1";
int x = log2(n);
if(((1<<(x+1)) - 1) == n){
string ans = "";
x++;
while(x--)ans+="0";
return ans;
}
return bin(n - (1<<x) + 1, x);
}
};
main(){
Solution ob;
cout << (ob.encode(23)) << endl;
cout << (ob.encode(56)) << endl;
}23 54
输出结果
1000 11001