列表

详情


NC253172. Lowbit

描述

One day Colin learned how to represent a number in binary form. For example, the binary form of (11)_{10} is (1011)_{2} , and he was very excited!

Further, Eva taught Colin a well-known binary function \text{lowbit}(x) which represents the value of the bit corresponding to the lowest 1 of x in binary form. For example, \text{lowbit}(11) = 1 , \text{lowbit}(4) = 4

Colin thought this function was amazing, so he thought of an interesting problem, and then it comes:

Given a binary form of a number x(x\le 2^{10^5}) , you need to perform some operations on x.
Each turn you can choose one of the following two operations: Now Colin wants to know, what is the minimum number of operations required to turn x into 0?

输入描述

A single line with the binary form of x \text{ } (1 \le x\le 2^{10^5}) without leading zero.

输出描述

One integer, the minimum number of operations required.

示例1

输入:

1100101

输出:

4

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

Python3 解法, 执行用时: 102ms, 内存消耗: 5576K, 提交时间: 2023-06-03 15:33:34

l=input()

l="0"+l
l=list(l)
Sum=0
k=0
for i in range(len(l)-1,0,-1):
    
    if l[i]=="1":
        k+=1
        if l[i-1]=="0" and k>1:
            Sum+=1
            l[i-1]="1"
            k=0
        elif l[i-1]=="0" and k==1:
            
            Sum+=1
            k=0
if l[0]=="1":
    Sum+=1
print(Sum)

pypy3 解法, 执行用时: 88ms, 内存消耗: 22116K, 提交时间: 2023-07-06 19:41:36

s = input()

s = s[::-1]+'0'
n = len(s)
ans = 0
fl = 0
for i in range(n):
    if s[i] == '1':
        fl += 1
    else:
        if fl == 1:
            fl = 0
            ans += 1
        elif fl == 0:
            continue
        else:
            fl = 1
            ans += 1

if fl >= 1:
    ans += 1
print(ans)

C++(clang++ 11.0.1) 解法, 执行用时: 6ms, 内存消耗: 664K, 提交时间: 2023-06-07 23:53:25

#include<bits/stdc++.h>
using namespace std;
int ans,sum;
int main(){
    string s;
    cin>>s,s="00"+s;//00101
    for (int i=s.size()-1;i>=0;i--){
    	if (s[i]=='1')	sum++;
    	else if (s[i]=='0'&&sum){
    		ans++;
			if (sum>1)	s[i]='1',sum=1;
			else sum=0;
		}
	}
	cout<<ans<<endl;
}

C++(g++ 7.5.0) 解法, 执行用时: 6ms, 内存消耗: 796K, 提交时间: 2023-07-09 11:56:42

#include<iostream>
using namespace std;
int ans,sum;
string s;
int main(){
	cin>>s;
	s="00"+s;
	for(int i=s.size()-1;i>=0;i--){
		if(s[i]=='1') sum++;
		else if(s[i]=='0'&&sum){
			ans++;
			if(sum>1) s[i]='1',sum=1;
			else sum=0;
		}
	}
	cout<<ans;
}

上一题