1342. Number of Steps to Reduce a Number to Zero

Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
Input: num = 123
Output: 12
  • 0 <= num <= 10^6
class Solution:
def numberOfSteps(self, num: int) -> int:
cnt=0
last=0
while(num):
last=[0,1][num&1]
if(last):
num-=1
else:
num//=2
cnt+=1
return(cnt)
class Solution:
def numberOfSteps(self, num: int) -> int:
cnt=0
last=0
while(num):
last=[0,1][num&1]
if(last):
num=num^1
else:
num>>=1
cnt+=1
return(cnt)

--

--

--

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Ingress: A Guide to configure on GKE

5 Shell commands to list down system’s configuration

Interface — Core Voilà

Flutter Sign in/Sign up: How to handle FirebaseAuthException

How to Install Laravel PHP Framework With Nginx on CentOS 8

If I absolutely can’t stop you from testing in production…

COMDEX; As A Persistence.one Product

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

More from Medium

Sum of All Subset XOR Totals

Some learning strategies and how Gympass helps their employees to grow up as professionals

Learning

Your Personal Brand Phase at Encora Apprenticeship — Week 2

Peer-to-peer: A conversation with Camila, one of our full-stack developers