Sum of Two Integers - Leetcode 371 - Java

preview_player
Показать описание


0:00 - Read the problem
1:40 - Drawing Explanation
9:47 - Coding Explanation

leetcode 371

#microsoft #interview #java
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
Рекомендации по теме
Комментарии
Автор

ok fine, I will compromise and start doing my videos in C 😉

NeetCode
Автор

If you want to do the same thing in Python, you can use this code (and I'll explain it!):

class Solution:
def getSum(self, a: int, b: int) -> int:
mask =

while b != 0:
tmp = (a & b) << 1
a = (a ^ b) & mask
b = tmp & mask

if a > mask // 2:
return ~(a ^ mask)
else:
return a

To explain, the hexadecimal number is the same as the binary number containing 32 1's. (It's just easier to type lol.)

In order to make the code work like Java, we want to treat our numbers like they only have 32 bits. ANDing a number with the mask or 32 1's, basically turns all of a number's bits into 0's except for the rightmost 32. As a result, the number can be represented as if it only has 32 bits.

We do what Neetcode describes in his video, using XOR for the sum and AND for the carry. We AND with the mask each time we set a and b in order to keep our numbers within 32 bits.

After we exit the while loop, we have our answer a. If a is positive, then we can return it directly. However, in Python, negative numbers are represented in binary as having an unlimited number of leading 1's. The current answer would only have values in the rightmost 32 bits. Therefore, if the answer is negative, we need to convert it into Python's representation of negative numbers.

First, we need to check if the answer is negative. We cannot just check to see if the answer is less than zero because our representation of the answer is not the same as Python's (since Python's have unlimited leading 1's). We are still treating our answer as if it only fits into 32 bits.

A 32-bit signed integer is positive if the 32nd bit is a 0 and is negative if the 32nd bit is a 1. If we divide our mask by 2, we will get the binary number which has 31 1's. This number is the greatest value we can have before the 32nd bit becomes a 1. Therefore, if our answer a > mask // 2, it is negative. Otherwise, it is positive and we can just return a itself.

If the number is negative, we then need to convert it into Python's representation of negative numbers. To do so, we can XOR with the mask of 32 1's in order to flip the rightmost 32 bits, since XORing a bit with 1 flips the bit. We can then NOT the number in order to turn all of the leading 0's into 1's. For example, say that the answer is -3, and or denote leading 0's or 1's until the 32nd bit:

Our representation of -3 in 32 bits:
XOR with mask, aka flip rightmost 32 bits:
NOT, aka flipping all bits:
The result is Python's representation of -3, including an unlimited number of leading 1's.

Overall, the code uses the same process as Neetcode's Java code, but with masking to get numbers into 32 bits and some manipulation to get those 32-bit numbers back into Python's representation before returning.

sysy
Автор

Thanks man for this. Just finished watching all your videos on the blind 75 list, I've learnt a lot.

thesouthsidedev
Автор

Please use python too in your future vids! There are many java based channels, but yours is the only good python channel that I could find

sia
Автор

9:31 Thanks for mentioning this. So that's why my python solution doesn't handle negative numbers.

tsunghan_yu
Автор

Thanks so much! You were the only one capable to clear in my mind these bitwise operations handled together. The use of the variable 'tmp', explaining its reason and its location on the code really clarified everything. Congrats for this awesome tutorial. God bless you. 🥰

siomarapantarotto
Автор

Thanks for code will work in Java but not worked same in C++ with negative number 🙃For C++
int getSum(int a, int b) {
while(b!=0)
{
unsigned int temp=(a&b);
a=a^b;
b=(int)(temp<<1);
}
return a;
}

akhileshsonkar
Автор

Hey man love your videos, your explanation is absolutely spot on: the default int val in python is too big.
For people crying about python, mask to limit int size to 32bit Don't spread hate people :) cheers
class Solution:
def getSum(self, a: int, b: int) -> int:

while b & mask:
a, b = (a ^ b), (a & b) << 1
return a & mask if b > 0 else a

msris
Автор

return Integer.sum(a, b); also works in a pinch! Java

osasikemwenogieva
Автор

Umm... I think I found out why Neet used Java. I converted it to Python but I got a time-limit exceed error. I guess Java automatically handles some of the edge cases (like when the input is a negative number ) :/ .

zg
Автор

This is fantastic. Now I can save the world without using any "+". ; )

mrmcyx
Автор

@NeetCode, can you please post the python solution? I tried converting your C solution to python but got a time limit exceeded error :(

johns
Автор

I prefer the Java because it’s more similar to other languages. Either way thanks for this great video

kilyos
Автор

Lol I like seeing everyone complain about this being Java...People, I'm a C++/C# programmer and I watch his Python videos.
It's not hard to convert one language to another...the point of these vids is to understand the algorithm and apply it!

dorondavid
Автор

How come if I use this solution in Python I get a Time Limit Exceeded error but it runs just fine with Java?

anahitahassan
Автор

can you explain why Python is not ideal for solving this binary question? Loved your logical approach and explanation in this video

jaslinkaur
Автор

Thank you so much for such a clear explanation! Very helpful!

ayeshaadhikari
Автор

I code in java. But I first come to Neetcode, listen to your explanation, go back and code in Java. My fav youtuber !

SatyaMantha
Автор

Is the microsoft logo at the beginning just random? Or is this problem tagged for microsoft?

eyyo
Автор

Is it cheeky to just create list = [a, b] and then return sum(list)? (It worked as a solution)

UKMatt
join shbcf.ru