Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Recursive Thinking approach (python)
YusufAdel
YusufAdel

Posted on • Edited on

     

Recursive Thinking approach (python)

Here's the code snippet with improved markdown formatting and readability:


A recursive definition is one which uses the word or concept being defined in the definition itself. Before applying recursion to programming, it is best to practice thinking recursively. Here I'm gonna to show you a good example for clarifying the purpose in detail.

Problem Statement:

The problem is finding the complement number of a binary format.

Example 1:

Input:

num = 5
Enter fullscreen modeExit fullscreen mode

Output:

2
Enter fullscreen modeExit fullscreen mode

Explanation:
The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input:

num = 1
Enter fullscreen modeExit fullscreen mode

Output:

0
Enter fullscreen modeExit fullscreen mode

Explanation:
The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

Constraints:

  • The given integer num is guaranteed to fit within the range of a 32-bit signed integer.
  • num >= 1
  • You could assume no leading zero bit in the integer’s binary representation.

Python Solution:

classSolution:deffindComplement(self,num:int)->int:# Convert num to binary formatbinary_num=bin(num)[2:]# '101'# Get complement by replacing every '0' with '1'new_binary_num=binary_num.replace('0','1')# '111'# Convert binary complement to integerint_num=int(new_binary_num,2)# 7# Calculate the difference to get the complementdifference=int_num-num# 7 - 5 = 2returndifference
Enter fullscreen modeExit fullscreen mode

Explanation:

  • Formatting the integer input to a proper binary to get processed, slicing it with[2:] to avoid the0b prefix as the output.
  • To get the complement, we replace every '0' with '1'.
  • We then turn it into the integer format again using the additionalint() argumentbase=2.
  • Finally, we calculate the difference, which represents the complement of the binary sequence.

Additional resources:
For curious readers


Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hi I'm Yusuf, I'm a junior Computer Science student interested in Open Source, Software Development and EngineeringI’m looking for internship opportunities in Software development and engineering.
  • Location
    Cairo, Egypt
  • Joined

More fromYusufAdel

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp