题目
解法1:
一板一眼的按照二进制来做
class Solution:def numSteps(self, s: str) -> int:def divide(s):return s[:-1]def add(s):carry = 1ans = ''for c in reversed(s):val = carry + int(c)remain = val%2ans = str(remain) + anscarry = val//2if carry:ans = str(carry) + ansreturn ans#print(divide('1110'))count = 0#for _ in range(7):while s!='1':if s[-1] == '0':s = divide(s)else:s = add(s)#print(s)count += 1return count
解法2:
直接转成十进制来做
class Solution:def numSteps(self, s: str) -> int:count = 0n = int(s, 2)while n > 1:if n % 2 == 1:count += 2n = (n+1)//2else:count +=1 n = n//2return count