Тёмный

Add Binary - Leetcode 67 - Python 

NeetCode
Подписаться 811 тыс.
Просмотров 59 тыс.
50% 1

Опубликовано:

 

11 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 85   
@NeetCode
@NeetCode 3 года назад
✏️ Have problem suggestions you would like me to solve? Feel free to comment them below :~)
@vijaychikkannavar5060
@vijaychikkannavar5060 2 года назад
last line should be return res[::-1] to reverse it back to original format
@sagargulati639
@sagargulati639 2 года назад
@@vijaychikkannavar5060 Yes you are right.
@DeeBall
@DeeBall Год назад
@@vijaychikkannavar5060 no
@subhashreesahoo6125
@subhashreesahoo6125 Год назад
Diagonal Matrix problem
@aaa_1711
@aaa_1711 7 месяцев назад
Why use ord?? Since we know it can either be 0 or 1. Why not just a string comparison and assign. Like, if it's "0", then digitA is 0, else 1 Same for digitB Good implementation though
@yoshi4980
@yoshi4980 3 года назад
an easy problem that can get boggled down in edge cases, really like some the tricks you used. great video as always!
@srinadhp
@srinadhp 3 года назад
Love the way you write the code. Concise. Love the loop of max of lengths. Great explanation as usual
@sanjayp7027
@sanjayp7027 3 года назад
how is this a easy problem :|
@LetCode96666
@LetCode96666 2 месяца назад
It's an easy but long problem for me. I solved it my way without any math 😅
@sunnilabeouf
@sunnilabeouf 3 года назад
Can't we just use int(a[i]) to cast it to an integer?
@NeetCode
@NeetCode 3 года назад
Yeah, you're right, I just remembered that. Thanks for pointing it out.
@surbhirohilla5139
@surbhirohilla5139 2 года назад
I was thinking the same and thougth what's the meaning of ord(0) which I can't understand😂lol, it was a mistake
@stove.d
@stove.d 2 года назад
@@surbhirohilla5139 ord() converts each string value to the integer representation of the unicode value (i.e. ASCII table), so subtracting ord("0") from ord("n") where 'n' is any number 0-9 will return that number. In ASCII, "0"=48 and "9"=57, so in that case `ord("9") - ord("0")` = 57 - 48 = 9
@rachnaramkumar
@rachnaramkumar 2 года назад
Isn't the time complexity quadratic since the addition of the 'char' string to the 'res' string copies all the contents and creates a new string for every loop since strings in python are immutable?
@ohyash
@ohyash 2 года назад
Yes. I'd append to the result string. And then reverse the string once in the end. Or push the result values to a stack and then form a result string in the end popping out from the stack.
@airysm
@airysm 3 года назад
Hi at 5:10, couldnt you use int() instead of ord() to cast the char?
@blaiserodrigues2990
@blaiserodrigues2990 3 года назад
Yes. you can.
@muzikjay
@muzikjay Год назад
"Let's go back to elementary school and add these together. What happens when we add 1 and 1?.....0?" 😂
@EmilyHopeGrove
@EmilyHopeGrove 6 месяцев назад
this...
@strawberriesandcream2863
@strawberriesandcream2863 2 года назад
thanks, you're a lifesaver when it comes to leetcode
@akhileshb5859
@akhileshb5859 2 года назад
You are a good teacher. Keep up the good work. Thank you!
@sriramkarthikakella2033
@sriramkarthikakella2033 Год назад
For converting it to integer, can we not do int(a[i]) and int(b[i]) instead of ord(a[i])-ord("0") and ord(b[i])-ord("0")?
@fadsa342
@fadsa342 Год назад
that worked for me in my solution
@alexgolomb363
@alexgolomb363 8 месяцев назад
Thank you for explaining what happens when you add "11" and "11". I was completely lost but not anymore thanks to you!
@beldam94
@beldam94 2 года назад
This code is simply beautiful. Thanks.
@vikasz2
@vikasz2 Год назад
def addBinary(self, a: str, b: str) -> str: a = int(a,2) b = int(b,2) res = a+b return bin(res)[2:]
@karthikkumaresan1091
@karthikkumaresan1091 2 года назад
What is the time complexity of the string concats in python(eg. char + res in the example above)
@clara8490
@clara8490 3 года назад
Amazing video and nice explanation!!!
@BurhanAijaz
@BurhanAijaz Год назад
we can use the same code for the question : leetcode 413(Add strings),just replace 2 by 10
@BurhanAijaz
@BurhanAijaz Год назад
code: class Solution: def addStrings(self, a: str, b: str) -> str: ans="" carry=0 a,b=a[::-1],b[::-1] for i in range(max(len(a),len(b))): digitA = ord(a[i])-ord('0') if i
@malh851
@malh851 9 месяцев назад
Great Explanation! Might be cleaner to use the divmod() function instead of % and //. Eg. char, carry = divmod(total, 2) res = str(char) + res
@sagargulati639
@sagargulati639 2 года назад
The returned res should be reversed to get the original output. return res[::-1]
@pranavsharma7479
@pranavsharma7479 2 года назад
nah see how is appending
@XzcutioneR2
@XzcutioneR2 Год назад
Why not just do bin(int(a, 2) + int(b, 2))[2:] ?
@seenumadhavan4451
@seenumadhavan4451 11 месяцев назад
There is no time complexity and space complexity mentioned in the problem. This should be fine i guess
@rohanvenkateshgupta2257
@rohanvenkateshgupta2257 2 года назад
Wonderful Explanation 👍👍👍
@triplestrikee875
@triplestrikee875 2 года назад
Very well explained, but don't we need to return res[::-1]?
@triplestrikee875
@triplestrikee875 2 года назад
Never mind, I thought res = char + res in the loop is same as res += char. My bad.
@ohyash
@ohyash 2 года назад
@@triplestrikee875 not the same.. Prepending char in the beginning of the string makes python have to copy all the result values everytime. It's better to append chars throughout and then reverse before returning in the end
@ShubhamShekhar-cm6rs
@ShubhamShekhar-cm6rs Год назад
Convert the array into non non-decreasing array by replacing elements with its subarray sum if necessary. for example, input=[3, 8, 5, 2, 10], output=[3,8,17] input=[1,2,3,4,5],output=[1,2,3,4,5] input=[5,4,3,2,1],output=[5,10] input=[],output=[] Please solve this problem.
@MaxFung
@MaxFung 9 месяцев назад
Youre an amazing teacher mr. neet!
@antoinenijhuis450
@antoinenijhuis450 8 месяцев назад
Why are we usig "ord" instead of "int(str)" ?? @NeetCode
@torontonian77
@torontonian77 2 года назад
one thing I never knew before is that you can use f-strings to convert int to binary. def binary_conversion(num): return f'{num:b}' so binary_conversion(1000) will get a result of 1111101000
@gagansuneja7029
@gagansuneja7029 2 года назад
we could have appended 0* (a.size - b.size) to the shorter string, saving time in reversal of both the strings. Later reversing the final string
@geraldakorli
@geraldakorli 9 месяцев назад
Why didn't you use int function on the values a[i] and b[i]?
@Salah-YT
@Salah-YT Год назад
thank u bro it is done and passed but I don't understand what I'm doing so what should I do to be better in Leetcode for everything I must find a tutorial so the tutorial killing me bro please help me out so more than a year I did a lot of HTML CSS javascript and 1000 of course and now python, why I can't, make a project and why I can't solve one easy problem in Leetcode or code war so I don't know bro and I fill I know everything but I can't code by my self must follow someone bro thx
@mehmetnadi8930
@mehmetnadi8930 2 года назад
is it normal to find "easy" questions hard? i mean i don't think most of the easy question are actually easy ngl :///
@NeetCode
@NeetCode 2 года назад
Absolutely, I struggled a lot with easy questions when I started. Eventually you will make progress!
@pcccmn
@pcccmn 2 года назад
yeah same feeling. I'm doing the Blind 75 Easy questions. Out of 20 questions I have attempted, I don't know how solve any :) It is what it is. I'm not smart, but that's ok. Traditional hardwork and repetition has never failed me. Good luck to you bro, for whatever reasons you're studying DSA.
@huhuboss8274
@huhuboss8274 Год назад
@@pcccmn how is it going? Did you improve?
@willd9807
@willd9807 2 года назад
I havent run the code, but did you get a character short each time from your reversing method. a,b = reversed(a), reversed(b)
@jankeshchakravarthy9389
@jankeshchakravarthy9389 Год назад
Nice explanation. Did you forget to reverse the result??
@ShivangiSingh-wc3gk
@ShivangiSingh-wc3gk 5 дней назад
I was thinking that the interviewer would want the bit manipulation solution for this
@aaa_1711
@aaa_1711 7 месяцев назад
Why use ord?? Since we know it can either be 0 or 1. Why not just a string comparison and assign. Like, if it's "0", then digitA is 0, else 1 Same for digitB Good implementation though
@abisheknair3545
@abisheknair3545 Год назад
int(a[i]) worked succesfully. so why did u use ord?
@chamahge3518
@chamahge3518 Месяц назад
i have a question for that carry = total//2 what if we add only 1 and 0 this still will give me a carry even though the result will be just 1 can anyone please help me with this?
@xmnemonic
@xmnemonic Год назад
should be medium
@duncanproctor7160
@duncanproctor7160 2 года назад
Why not just pad the shorter string with leading zeros?
@Levelord92
@Levelord92 Год назад
interesting...
@fadsa342
@fadsa342 Год назад
that's what I did. I guess technically by padding you're taking up more space and the operation isn't free since you're creating a new string and iterating over the existing one.
@andrewromanenkov6929
@andrewromanenkov6929 2 года назад
Answer in 2 lines of code: c = bin(int(a,2) + int(b,2)) return c[2:]
@willd9807
@willd9807 2 года назад
print(eval())
@ohyash
@ohyash 2 года назад
Interviewer: _Pikachu face_
@Levelord92
@Levelord92 Год назад
yeah, put 9223372036854775807 and 9223372036854775807 as summands and see what happens, genius
@mruduladdipalli5417
@mruduladdipalli5417 Год назад
I implemented same approach for Dart, it gave Time Limit Exceeded, but for java it worked :(
@RobertMcHalffey
@RobertMcHalffey 9 месяцев назад
Python solution converted to JavaScript: var addBinary = function(a, b) { let totalSum = ''; let carry = 0; a = a.split('').reverse().join(''); b = b.split('').reverse().join(''); for (let i = 0; i < Math.max(a.length, b.length); i++){ const digitA = parseInt(i < a.length ? a[i] : 0); const digitB = parseInt(i < b.length ? b[i] : 0); const total = digitA + digitB + carry; const currentSum = total % 2; totalSum = currentSum + totalSum; carry = Math.floor(total / 2); } return carry ? 1 + totalSum : totalSum; };
@meetugupta602
@meetugupta602 2 года назад
can someone tell my error niothing is shown in the output class Solution { public: string solve(string a , string b){ int countfirst=0; int diff = a.size()-b.size(); // int countsecond=0; string s; int carry=0; for(int i=b.size()-1;countfirst > b.size();i--){ if (a[i + diff] + b[i] + carry == 0){ carry=0; s.push_back(0); } else if (a[i + diff] + b[i] + carry == 1){ carry=0; s.push_back(1); } else if (a[i + diff] + b[i] + carry == 2){ carry = 1; s.push_back(0); } else if (a[i + diff] + b[i] + carry == 3){ carry=1; s.push_back(1); } countfirst++; } for(int i=a.size()-b.size()-1;i>=0;i--){ if (a[i] + carry == 0){ carry=0; s.push_back(0); } else if (a[i] + carry == 1){ carry=0; s.push_back(1); } else if (a[i] + carry == 2){ carry=1; s.push_back(0); } } if (carry == 1){ s.push_back(1); } // reverse(s.begin() , s.end()); return s; } string addBinary(string a, string b) { if (a.size() >= b.size()){ string s = solve(a,b); return s; } string s=solve(b,a); return s; } };
@aniruddh3423
@aniruddh3423 2 года назад
idk if this counts as cheating but return str(bin(int(a,2)+int(b,2)))[2:]
@edwardteach2
@edwardteach2 3 месяца назад
U a binary God
@FaizanShaikh-zg9to
@FaizanShaikh-zg9to Год назад
Hello I hava a doubt can we use inbuild function like bin class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a, 2) + int(b, 2))[2:] the code works pretty efficiently but is it the right way?
@sabrish7263
@sabrish7263 3 года назад
Why not bin to int -> add 2 ints-> int to bin and return
@NeetCode
@NeetCode 3 года назад
Yeah, I think that's also a valid solution
@stan8851
@stan8851 3 года назад
I don't think the interviewer want to see this solution, they want to see how you deal with the edge cases of this problem
@roshni962
@roshni962 3 года назад
@@NeetCode Wont work for INT_MAX
@AntaroopGhosh
@AntaroopGhosh 2 года назад
class Solution: def addBinary(self, a: str, b: str) -> str: a1=int(a,2) b1=int(b,2) sum1=a1+b1 return bin(sum1)[2:]
@NN-uy6ik
@NN-uy6ik 2 года назад
Incredible 😮😮😮😮
@akashThe99
@akashThe99 Год назад
the second example showing wrong answer with this solution
@rddcol
@rddcol Год назад
How is this supposed to be easy 😭😭😭😭😭😭😭. Not understanding shit . Somebody tell me where to start ;
@shadowfiend8549
@shadowfiend8549 Год назад
i was not even able to solve this one is this abnormal ?
@dynaspinner64
@dynaspinner64 6 месяцев назад
We all start from somewhere. Once you practice enough easys and re do them you will find them easy.
@Levelord92
@Levelord92 Год назад
Come on... this is really an "Easy" task?
@diptopodder1011
@diptopodder1011 Год назад
class Solution: def addBinary(self, a: str, b: str) -> str: s1 = int(a, 2) s2= int(b, 2) s=s1+s2 return bin(s).replace("0b", "")
@Jaffar87
@Jaffar87 2 года назад
solve all leetcode problems
Далее
How I would learn Leetcode if I could start over
18:03
Просмотров 499 тыс.
LeetCode 67. Add Binary Solution Explained - Java
10:24
А ВЫ ЛЮБИТЕ ШКОЛУ?? #shorts
00:20
Просмотров 1,9 млн
Sqrt(x) - Leetcode 69 - Python
8:34
Просмотров 57 тыс.
Cursor Is Beating VS Code (...by forking it)
18:00
Просмотров 71 тыс.
OpenAI Strawberry is LIVE
Просмотров 4,6 тыс.
Merge Sorted Array - Leetcode 88 - Python
10:18
Просмотров 211 тыс.
Jump Game - Greedy - Leetcode 55
16:28
Просмотров 236 тыс.
3Sum - Leetcode 15 - Python
12:54
Просмотров 800 тыс.
Balanced Binary Tree - Leetcode 110 - Python
13:11
Просмотров 243 тыс.
А ВЫ ЛЮБИТЕ ШКОЛУ?? #shorts
00:20
Просмотров 1,9 млн