LeetCode #7: Reverse Integer

preview_player
Показать описание
0:00 Intro
0:28 Overview of how bits work
2:12 Positive integer example
5:53 Negative integer example
8:13 Overflow example
9:27 Do we need to check the value of the last digit?

#programming #coding #algorithms
Рекомендации по теме
Комментарии
Автор

Hey! Great explanation.

But I had a solution which was a little easy for me to go with. Do you mind comparing and telling me which one is better in terms of everything?

## Reverse Integer

class Solution:
def reverse(self, x: int) -> int:

x = str(x)
if len(x) == 1:
return int(x)

sign = ''
if x[0] == '-':
sign = x[0]
x = x[1:]
rev_num = x[::-1]
final_answer = int(sign + rev_num)

if final_answer < -2**31 or final_answer > 2**31 - 1:
return 0
return final_answer

rsk_
Автор

why does it return 0 for -321 in leetcode

billionyears
Автор

Saw your solution on Leetcode and realized that your overflow checker is not good. It only checks if reverse > MAX_INT/10 or reverse*10 > MAX_INT but doesn't check if reverse*10 + digit might overflow before it's calculated. Essentially you should be using reverse > MAX_INT/10 - digit/10 as your checking expression.

kaustuvprateeq