0
点赞
收藏
分享

微信扫一扫

[leetcode] 1404. Number of Steps to Reduce a Number in Binary Representation to One

香小蕉 2022-08-11 阅读 16


Description

Given a number s in their binary representation. Return the number of steps to reduce it to 1 under the following rules:

  • If the current number is even, you have to divide it by 2.
  • If the current number is odd, you have to add 1 to it.

It’s guaranteed that you can always reach to one for all testcases.

Example 1:

Input: s = "1101"
Output: 6
Explanation: "1101" corressponds to number 13 in their decimal representation.
Step 1) 13 is odd, add 1 and obtain 14.
Step 2) 14 is even, divide by 2 and obtain 7.
Step 3) 7 is odd, add 1 and obtain 8.
Step 4) 8 is even, divide by 2 and obtain 4.
Step 5) 4 is even, divide by 2 and obtain 2.
Step 6) 2 is even, divide by 2 and obtain 1.

Example 2:

Input: s = "10"
Output: 1
Explanation: "10" corressponds to number 2 in their decimal representation.
Step 1) 2 is even, divide by 2 and obtain 1.

Example 3:

Input: s = "1"
Output: 0

Constraints:

  • 1 <= s.length <= 500
  • s consists of characters ‘0’ or ‘1’
  • s[0] == ‘1’

分析

题目的意思是:给定一个二进制字符串,按照规则把它变为1,最简单粗暴的方法就是把字符串变成整数,然后按照规则计算,当然我觉得太过粗暴了,不是题目的本意。变换一下思路,如果当前的数是偶数,直接除以2,相当于把字符串最后一位舍弃掉;如果当前的数是奇数,从后往前遍历,找到第一个为0的位置然后置1,遍历过程中的1当然要置0了哈。这样就模拟实现了二进制的+1操作。

代码

class Solution:
def numSteps(self, s: str) -> int:
arr=list(s)
res=0
while(arr!=['1']):
if(arr[-1]=='0'):
arr=arr[:-1]
else:
flag=True
for i in range(len(arr)-1,-1,-1):
if(arr[i]=='1'):
arr[i]='0'
else:
arr[i]='1'
flag=False
break
if(flag):
arr=['1']+arr
res+=1
return res

参考文献

​​[LeetCode] [Python3] O(N) Solution, Bit Manipulation​​


举报

相关推荐

0 条评论