B. Population Count
给出一个数据范围 ,求这个范围里面所有整数的二进制形式中
1
的数目。
- 位运算的应用
- 代码
#include <bits/stdc++.h>
using namespace std;
int solve(int n)
{
int ans(0);
while(n)
{
if(n & 1 == 1)
ans++;
n >>= 1;
}
return ans;
}
int main()
{
int t;
cin >> t;
while(t--)
{
int b, e, sum(0);
cin >> b >> e;
for(int i = b; i<=e; i++)
{
sum += solve(i);
}
cout << sum << endl;
}
return 0;
}
F. Sequence Decoding
如例:输入2[pphh],输出pphhpphh;
输入2[2[ph]h],输出phphhphphh;
- 字符串的相关问题。
- 当时是直接搜了一下
string
的一些用法就拿来用了,基本上思路正确靠着基本用法就可以做出来。详细思路都注释在代码里了。 - 代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
string str;
cin >> str;
if(str.find("]") > str.length()) ///判断是否有括号
cout << str << endl;
else
{ ///将最内层的括号进行替换,直至所有括号替换成需要扩展的字母串
while(str.find("[") < str.length()) ///判断是否有括号
{
int index = str.find("]"); ///从左往右找到第一个右中括号的位置
///找到与之匹配的左中括号的位置
int index1;
for(int i = index; ;i--)
{
if(str[i] == '[')
{index1 = i; break;}
}
///将当前括号内的字母串找出来,并按照括号前的数字成倍扩展
string str1 = str.substr(index1+1, index-index1-1);///截取括号内字母串
string str2;
int ans = str[index1-1] - '0';///得到扩大倍数
while(ans--) str2 += str1;///得到扩展后的字母串
///将括号、括号内的字母串、括号前的数字替换成扩展后的字母串
str = str.replace(index1-1, index-index1+2,str2);
}
cout << str << endl;
}
}
return 0;
}