L - Binary String
A binary string is a non-empty sequence of 00's and 11's, e.g., 010110, 1, 11101, etc. Ayu has a favorite binary string SS which contains no leading zeroes. She wants to convert SS into its decimal representation with her calculator.
Unfortunately, her calculator cannot work on any integer larger than KK and it will crash. Therefore, Ayu may need to remove zero or more bits from SS while maintaining the order of the remaining bits such that its decimal representation is no larger than KK. The resulting binary string also must not contain any leading zeroes.
Your task is to help Ayu to determine the minimum number of bits to be removed from SS to satisfy Ayu's need.
For example, let SS = 1100101 and K=13K=13. Note that 1100101 is 101101 in decimal representation, thus, we need to remove several bits from SS to make it no larger than KK. We can remove the 3rd3rd, 5th5th, and 6th6th most significant bits, i.e. 1100101 →→1101. The decimal representation of 1101 is 1313, which is no larger than K=13K=13. In this example, we removed 33 bits, and this is the minimum possible (If we remove only 22 bits, then we will have a binary string of length 55 bits; notice that any binary string of length 55 bits has a value of at least 1616 in decimal representation).
Input
Input begins with a line containing an integer KK (1≤K≤2601≤K≤260) representing the limit of Ayu's calculator. The second line contains a binary string SS (1≤|S|≤601≤|S|≤60) representing Ayu's favorite binary string. You may safely assume SS contains no leading zeroes.
Output
Output contains an integer in a line representing the minimum number of bits to be removed from SS.
Examples
Input
13 1100101
Output
3
Input
13 1111111
Output
4
Note
Explanation for the sample input/output #1
This sample is illustrated by the example given in the problem description above.
Explanation for the sample input/output #2
Ayu must remove 44 bits to get 111, which is 77 in its decimal representation.
题意:
给你一个整数 (n)和 0、1字符串(text),通过尽可能少的操作数(ans)删除text中的字符(优先删除‘1’,因为‘0’的贡献比较小),使得text的十进制数<=n。输出ans。数据保证最高有‘1’。
思路:
将字符串(text)转化 十进制数(sum)与 整数(n)比较。
求出最高位的贡献(tmp),在每次删除‘1’的时候,要减去(最高位与第二个最高位的差值)和 (此位置上的贡献值)。
题解:
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=105;
long long n,m;
char text[maxn];
int main()
{
int lm,lt,ans=0;
ll sum=0,k=1,tmp;
scanf("%lld",&n);
getchar();
scanf("%s",text);
lt=strlen(text);
tmp=(ll)k<<(lt-1); //最高位的贡献
for(int i=0;i<lt;i++)
{
if(text[i]=='1')
sum += k<<(lt-1-i); //text的十进制
}
bool flag=0;
for(int i=0;i<lt;i++)
{
if(text[i]=='1'&&!flag) //前导不为‘0’
{
flag=1;
continue;
}
if(sum<=n)
break;
if(flag&&text[i]=='1')
{
sum-=k<<(lt-i-1);
sum-=(tmp-tmp/2);
tmp>>=1;
ans++;
}
}
while(sum>n) //删除‘0’
{
sum>>=1;
ans++;
}
printf("%d\n",ans);
return 0;
}