Multiply using bits -- is my coding style / solution good enough?


  • 0
    P

    Honestly feel like my code is pretty ugly.. it also took me awhile to come up with this solution which is kinda embarassing and not a good sign. Any thoughts?

    
    def mul_bits(x,y):
    	temp = 0
    	for i in range(0, x.bit_length()):
    		xbit = (x >> i) & 1
    		cum = temp
    		temp = 0
    		for j in range(0, y.bit_length()):
    			ybit = (y >> j) & 1
    			if xbit & ybit == 1:
    				temp |= (1 << (j+i))
    		temp = add_bits(temp, cum)
    	return temp
    
    def add_bits(x,y):
    	total = 0
    	length = max(x.bit_length(), y.bit_length())
    	carry = 0
    	for i in range(0, length):
    		xbit = (x >> i) & 1
    		ybit = (y >> i) & 1
    		if xbit ^ ybit == 1:
    			if carry == 1:
    				carry = 1
    			else:
    				total |= (1 << i)
    				carry = 0
    		elif xbit & ybit == 1:
    			if carry == 1:
    				total |= (1 << i)
    			carry = 1
    		else:
    			if carry == 1:
    				total |= (1 << i)
    			carry = 0
    	if carry == 1:
    		total |= (1 << length)
    	return total

Log in to reply
 

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