当前位置: 代码迷 >> 综合 >> Leetcode 1404. Number of Steps to Reduce a Number in Binary Representation to One (python)
  详细解决方案

Leetcode 1404. Number of Steps to Reduce a Number in Binary Representation to One (python)

热度:78   发布时间:2023-11-26 06:19:22.0

题目

在这里插入图片描述

解法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
  相关解决方案