按规则编码解码类问题
这道题是 2021-9-17 网易笔试第一道题
题目描述
最近,小易想出了对任意一个十进制正整数求它“易数”的方法。假设正整数是
X
X
X,求易数规则如下:
(1) 对
X
X
X 的每个数字分别使用最少位数的二进制表示,如
21370
t
o
101111110
21370 \;\;to \;\;101111110
21370to101111110,其中
2
t
o
(
10
)
,
1
t
o
(
1
)
,
3
t
o
(
11
)
,
7
t
o
(
111
)
,
0
t
o
0
2\;\;to\;\;(10), 1\;\;to\;\;(1), 3\;\;to\;\;(11), 7\;\;to\;\;(111), 0\;\;to\;\;0
2to(10),1to(1),3to(11),7to(111),0to0 。得到
A
A
A。
(2) 对
A
A
A 进行翻转,去掉前导
0
0
0,如
101111110
t
o
11111101
101111110 \;\; to \;\; 11111101
101111110to11111101,得到
B
B
B。
(3) 对
B
B
B,所有相邻的
1
1
1,如果数量多于
1
1
1 个,则只保留
1
1
1 个,对于所有相邻的
0
0
0 也是同样处理。如
11111101
t
o
101
11111101\;\; to\;\; 101
11111101to101。得到
C
C
C。
Input: 2
10
99
Output:1
10101
输入描述:
输入第一行为正整数
T
T
T,表示数据组数。接下来每组数据为一个正整数
N
N
N,表示范围。
数据范围:
对于
30
%
30\%
30% 数据,满足
1
<
=
T
<
=
50
,
1
<
=
N
<
=
300
1 <= T <= 50, 1 <= N <= 300
1<=T<=50,1<=N<=300
对于
70
%
70 \%
70% 数据,满足
1
<
=
T
<
=
50
,
1
<
=
N
<
=
3000
1 <= T <= 50, 1 <= N <= 3000
1<=T<=50,1<=N<=3000
对于所有数据,满足
1
<
=
T
<
=
50
,
1
<
=
N
<
=
30000
1 <= T <= 50, 1 <= N <= 30000
1<=T<=50,1<=N<=30000
题解
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
string a;
while(n)
{
int tt = n % 10;
if(tt)
{
while(tt)
{
a += to_string(tt & 1);
tt >>= 1;
}
}
else
{
a += "0";
}
n /= 10;
}
int idx = 0;
while(a[idx] == '0') idx++;
string b = a.substr(idx);
string c;
char tmp = '';
for(int i=0; i<b.size(); ++i)
{
if(b[i] == tmp) continue;
c.push_back(b[i]);
tmp = b[i];
}
int res = 0;
for(int i=0; i<c.size(); ++i)
{
res = res * 10 + (c[i] - '0');
}
cout << c << endl;
}
return 0;
}