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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值