my different approach & easy explanation - Python3 [Number Complement]


  • 0
    P

    What I thought

    1. Change given 'num'(number) to binary number.
    • bin(num)

    1. Convert '0' to '1' , '1' to '0'. (For example, 10100 -> 01011)
    • a = '' (an empty string)
    • if '0' appears, add '1' to a.
    • if '1' appears, add '0' to a.

    1. Convert a string 'a' (binary number) to integer. (For example, if a is 100, return 4.)
    • eval('0b' + a)

    Question & Answer

    • Q1. binary number starts with '0b'. For example, bin(11) is '0b1011'. If I change '0' to '1', '1' to '0', '0b1011' will be '1b0100' and this will be a wrong answer.

    • A1. bin() is a function changing number to binary number. By the way, the type of this binary number is 'string'.

    >>> type(bin(11))
    <class 'str'>
    

              Therefore, we can use bin(num)[2:]

    >>> bin(11)
    '0b1011'
    >>> bin(11)[2:]
    '1011'
    

    • Q2. Does eval(a) work?

    • A2. No. For example,

    >>> bin(11)
    '0b1011'
    >>> bin(11)[2:]
    '1011'
    >>> eval('1011')
    1011
    

            What about eval('0b'+'1011')?

    >>> bin(11)
    '0b1011'
    >>> bin(11)[2:]
    '1011'
    >>> eval('0b1011')
    11
    


    My Solution

    class Solution:
        def findComplement(self, num):
            num=bin(num)[2:]
            a=''
            for i in range(len(num)):
                if num[i]=='0':
                    a=a+'1'
                else:
                    a=a+'0'
            return eval('0b'+a)
    

    And there are lots of different and simple good solutions: using 2**N , len() or using xor..

    What is your solution?
    Please share your thoughts and let me know if you have any questions.


  • 1
    P

    I recommend to read this solution by @prasanna_date (with easy, kind explanation! ) : Easy to understand Python solution O(1)[Click]

    Much Better than my approach!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.