NC253172. Lowbit
描述
输入描述
A single line with the binary form of 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; }