Reverse integer python leetcode

Reverse Integer – Leetcode Solution

In this post, we are going to solve the 7. Reverse Integer problem of Leetcode. This problem 7. Reverse Integer is a Leetcode medium level problem. Let’s see code, 7. Reverse Integer.

Problem

Given a signed 32-bit integer x , return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2 31 , 2 31 — 1] , then return 0 .

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1 :

Example 2 :

Example 3 :

Constraints

Now, let’s see the code of 7. Reverse Integer – Leetcode Solution.

Reverse Integer – Leetcode Solution

7. Reverse Integer – Solution in Java

class Solution < public int reverse(int x) < int num = x; long rev = 0; while(num != 0)< int digit = num%10; rev = 10*rev + digit; if(rev >Integer.MAX_VALUE)return 0; if(rev < Integer.MIN_VALUE)return 0; num/=10; >return (int)rev; > >

7. Reverse Integer – Solution in C++

class Solution < public: int reverse(int x) < int num = x; long int rev = 0; while(num != 0)< int digit = num%10; rev = 10*rev + digit; if(rev >INT_MAX)return 0; if(rev < INT_MIN)return 0; num/=10; >return (int)rev; > >;

7. Reverse Integer – Solution in Python

class Solution: def reverse(self, x): result = 0 if x < 0: symbol = -1 x = -x else: symbol = 1 while x: result = result * 10 + x % 10 x /= 10 return 0 if result >pow(2, 31) else result * symbol

Note: This problem 7. Reverse Integer is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Источник

LeetCode #7 — Reverse Integer

Hello fellow devs 👋! It’s a new day and it’s time for looking into another LeetCode problem.

Given a 32-bit signed integer, reverse digits of an integer.

Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2 31 , 2 31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

This problem is pretty straightforward 😄. To reverse an integer, we only have to make most significant digit as the least significant digit and vice versa, the second most significant digit to the second least significant digit and vice versa and so on.

Читайте также:  New http request php

There are couple of things we need to keep in mind —

  1. If the input is negative, the output will also be negative
  2. If the input is greater than the given range (−2 31 , 2 31 − 1), return 0.
  1. First we find out if the number is negative then we will store this information.
  2. First store the result in a data type which is bigger than an integer (for e.g., long in case of Java/Kotlin)/
  3. Divide the number repeatedly by 10 until the number becomes zero.
  4. After the loop check if the output is greater than the range (−2 31 , 2 31 − 1).
  5. At last, return the output with the correct sign (positive or negative).

Since we are going through the entire number digit by digit, the time complexity should be O(log10n). The reason behind log10 is because we are dealing with integers which are base 10.

We are not using any data structure for interim operations, therefore, the space complexity is O(1).

public class ReverseInteger  public int reverse(int x)  boolean isNegative = false; if (x  0)  isNegative = true; x = -x; > long reverse = 0; while (x > 0)  reverse = reverse * 10 + x % 10; x /= 10; > if (reverse > Integer.MAX_VALUE)  return 0; > return (int) (isNegative ? -reverse : reverse); > >
def reverse(x: int) -> int: isNegative = False if x  0: isNegative = True x = -x reversedNumber = 0 while x: reversedNumber = reversedNumber * 10 + x % 10 x //= 10 if reversedNumber >= 2 ** 31 - 1 or reversedNumber  -2 ** 31: return 0 return -reversedNumber if isNegative else reversedNumber
var reverse = function(x)  let isNegative = false; if (x  0)  isNegative = true; x = -x; > let reverse = 0; while (x > 0)  reverse = reverse * 10 + x % 10; x = parseInt(x / 10); > if (reverse >= Math.pow(2, 31) - 1 || reverse  Math.pow(-2, 31))  return 0; > return isNegative ? -reverse : reverse; >;
fun reverse(x: Int): Int  var num = x var isNegative = false if (num  0)  isNegative = true num = -num > var reverse: Long = 0 while (num > 0)  reverse = reverse * 10 + num % 10 num /= 10 > return if (reverse > Int.MAX_VALUE)  0 > else (if (isNegative) -reverse else reverse).toInt() >

Today we discussed how to solve LeetCode problem — Reverse integer.

I hope you have enjoyed this post. Feel free to share your thoughts on this.

You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.

Till next time… Happy coding 😄 and Namaste 🙏!

Источник

How to reverse an integer in Python | LeetCode Practice

Constrains:
If the integer is outside the range [−2**31, 2**31 − 1] return 0.

Have a go at it and let’s compare our solutions!

Solution

First I will post my solution then go though the reasoning behind it:

def reverse(self, x: int) -> int: if x  0: x = str(x)[1:][::-1] while x[0] == '0': x = x[1:] x = 0-int(x) if x  -2**31: return 0 return x else: if x 10: return x x = str(x)[::-1] while x[0] == '0': x = x[1:] x = int(x) if x > (2**31)-1: return 0 return x 

I’ve chosen to tackle this in 2 scenarios: when x < 0 and when x is >=0. Let’s start with x < 0.

First we turn x into a string, remove the ‘-‘ and reverse it. All of that is being taken care of by this line:

An example of what the above line does: -123 -> ‘-123’ -> ‘123’ -> ‘321’

If the new string has ‘0’ at the beginning, we use a while loop to remove all the zeros until we find a non-zero character:

Then we turn x back into a negative integer and check if it is within the size constraint. If it is we return x otherwise we return 0:

x = 0-int(x) if x  -2**31: return 0 return x 

Next we will look at the case when x >= 0.

Next we follow the same logic as above. We turn it into a string and reverse it:

We strip it of 0s if there are any at the beginning of the string:

We turn it back into an integer and check against the constrains. If it doesn’t meet the size requirements we return 0, otherwise return x:

x = int(x) if x > (2**31)-1: return 0 return x 

This was my solution, let me know if you had a different one!

Also if you want you can follow me here or on Twitter 🙂

Источник

Задача “Reverse Integer” с LeetCode, решение на Python

Учитывая 32-разрядное целое число со знаком x , верните x его цифры в обратном порядке. Если обращение вспять x приводит к выходу значения за пределы диапазона 32-разрядных целых чисел со знаком [-2 31 , 2 31 — 1] , затем верните 0 .

Предположим, что среда не позволяет хранить 64-разрядные целые числа (со знаком или без знака).

© LeetCode Problems

Пример входных и выходных данных программы от LeetCode:

Ввод: x = 123 Вывод: 321

Ограничения, которые предоставляет LeetCode:

Решение Reverse Integer, полный код:

class Solution: def reverse(self, x: int) -> int: negative = x < 0 if negative: x = -x reversed_x = 0 max_int = (1 0: digit = x % 10 if reversed_x > max_int // 10 or (reversed_x == max_int // 10 and digit > max_int % 10): return 0 if reversed_x < min_int // 10 or (reversed_x == min_int // 10 and digit < min_int % 10): return 0 reversed_x = reversed_x * 10 + digit x //= 10 if negative: return -reversed_x else: return reversed_x

Разбор решения Reverse Integer с LeetCode

Функция reverse принимает на вход целое число x и возвращает число, полученное из x путем разворота его цифр. Если результат выходит за пределы диапазона знаковых 32-битных целых чисел, то функция возвращает 0.

Алгоритм решения этой задачи работает следующим образом:

  1. Проверить, является ли число x отрицательным, с помощью сравнения x < 0 , и сохранить этот факт в переменной negative .
  2. Если x отрицательное, сделать его положительным, умножив на -1, чтобы избежать проблем с обработкой знака во время разворота цифр.
  3. Создать переменную reversed_x и инициализировать ее значением 0. Эта переменная будет использоваться для хранения результата разворота цифр числа x .
  4. Создать переменные max_int и min_int для хранения максимального и минимального значения 32-битного знакового целого числа соответственно.
  5. В цикле while выполнять следующие шаги, пока x больше 0:
    • Получить последнюю цифру числа x , используя операцию остатка от деления на 10 ( x % 10 ), и сохранить ее в переменной digit .
    • Проверить, что результат разворота цифр reversed_x умноженного на 10 и увеличенного на digit не выходит за пределы диапазона знаковых 32-битных целых чисел, сравнивая его со значением max_int // 10 и max_int % 10 .
    • Если результат разворота цифр reversed_x выходит за пределы максимального значения, вернуть 0.
    • Проверить, что результат разворота цифр reversed_x умноженного на 10 и увеличенного на digit не выходит за пределы диапазона знаковых 32-битных целых чисел в отрицательную сторону, сравнивая его со значением min_int // 10 и min_int % 10 .
    • Если результат разворота цифр reversed_x выходит за пределы минимального значения, вернуть 0.
    • Обновить значение reversed_x , умножив его на 10 и добавив digit .
    • Убрать последнюю цифру из x , разделив его на 10 с использованием оператора целочисленного деления ( x //= 10 ).
  6. После выхода из цикла вернуть значение reversed_x с сохранением оригинального знака числа x в случае, если x было отрицательным, или без изменений в противном случае.

Источник

Оцените статью