当前位置:网站首页>Reverse Integer
Reverse Integer
2022-07-25 14:07:00 【The goal is technology house】
LeetCode
subject : Reverse Integer
Python
Title Description :
Given a 32-bit signed integer, reverse digits of an integer.
Example :
Input: 123
Output: 321 There is a special point in the title :32 position Integers ,32 The range of bit integers is [-2147483648, 2147483647].
If it's beyond that range , Then it's time to go back 0.
And in python in ,a/10 If not completely divisible , The result of direct calculation is floating point number . Need to use int(a/10).
I didn't notice this at the beginning of the question .
The result of solving the problem by yourself , It may be more cumbersome than that of the great God , But the idea is relatively clear :
1. Treat negative numbers as positive numbers .
2. Store data bit by bit in the list , From the last digit of the original number to the first digit, it is stored in the list . If the list is empty and the last few digits of the original number are 0, Don't put it in the list .
3. Restore data upside down .
4. Judge the range of converted data , Is it a positive number or a negative number , Or more than 32 Range of bit data .
class Solution:
def reverse(self, x):
flag = 0
if x < 0:
flag = 1
x = 0 - x
a = x
b = []
while a != 0:
if len(b) == 0 and a % 10 == 0:
a = int(a / 10)
continue
b.append(a % 10)
num = 0
k = 1
for i in range(len(b)):
j = len(b) - 1 - i
num += b[j] * k
k = k * 10
if flag == 0 and num <= 2**31-1:
return num
elif flag == 1 and num <= 2**31:
return -num
else:
return 0The complexity of time and space is O(log n)
The correct answer is C++ edition :
The advantage of the algorithm is The space complexity is O(1) as well as The way to judge .
The space complexity is O(1):
Get a remainder each time , All directly Previous multiplication 10 Add the new remainder . So you don't have to put the remainder in the list .
The way to judge :
Before every ride , Judge rev Whether it will exceed 32 The range of bits . If not beyond , Then continue to multiply .
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
};in addition : The following code can detect whether x There's spillover .
if (x * 10 / 10 !== x) {
// overflow
} however Python Written words , You can't follow this completely . because :
1.a/10 If it's not divisible , What you get is a floating point number This has already been mentioned .
2. stay Python in ,-123%10 be equal to 7, This with C++ and Java The treatment of is different . Therefore, we need to judge the positive and negative numbers in advance .
Python version:
class Solution:
def reverse(self, x):
num = 0
a = abs(x)
while(a != 0):
pop = a % 10
num = num * 10 + pop
a = int(a / 10)
if x > 0 and num < 2**31:
return num
elif x < 0 and num <= 2**31:
return -num
else:
return 0 Of course, there are more ingenious methods :
Reverse the order after converting to a string :
class Solution:
def reverse(self, x):
a = int(str(abs(x))[::-1])
if a > 2**31 or (a == 2**31 and x > 0):
return 0
elif x > 0:
return a
else:
return -a边栏推荐
- Day1:三种语言暴刷牛客130题
- Leetcode1 -- sum of two numbers
- 科隆新能源IPO被终止:拟募资6亿 先进制造与战新基金是股东
- opencv视频跟踪「建议收藏」
- [directory blasting tool] information collection stage: robots.txt, Yujian, dirsearch, dirb, gobuster
- 数字孪生 - 认知篇
- 依迅总经理孙峰:公司已完成股改,准备IPO
- Workplace "digital people" don't eat or sleep 007 work system, can you "roll" them?
- Deep understanding of pytorch distributed parallel processing tool DDP -- starting from bugs in engineering practice
- Famous handwritten note taking software recruit CTO · coordinate Shenzhen
猜你喜欢

数字孪生 - 认知篇

Advantages of wireless relay acquisition instrument and wireless network for engineering monitoring

AI model risk assessment Part 1: motivation

Construction and practice of yolov7 in hands-on teaching

依迅总经理孙峰:公司已完成股改,准备IPO

Brush questions - Luogu -p1161 turn on the light

Business analysis report and data visualization report of CDA level1 knowledge point summary
知名手写笔记软件 招 CTO·坐标深圳

What you must know about data engineering in mlops

实现一个家庭安防与环境监测系统(二)
随机推荐
金鱼哥RHCA回忆录:CL210管理存储--管理共享文件系统
Acquisition data transmission mode and online monitoring system of wireless acquisition instrument for vibrating wire sensor of engineering instrument
NUC980 设置SSH Xshell连接
Common problems of wireless relay acquisition instrument
Detailed explanation of how R language converts large Excel files into DTA format
Three ways of redis cluster
maya建模练习
NAT/NAPT地址转换(内外网通信)技术详解【华为eNSP】
sieve of eratosthenes
2271. 毯子覆盖的最多白色砖块数 ●●
[configure hifive1 revb] the device manager does not recognize the port, and can not connect to j-link via USB
Typora无法打开提示安装新版本解决办法
Cologne new energy IPO was terminated: the advanced manufacturing and Zhanxin fund to be raised is the shareholder
The practice of depth estimation self-monitoring model monodepth2 in its own data set -- single card / multi card training, reasoning, onnx transformation and quantitative index evaluation
力扣(LeetCode)205. 同构字符串(2022.07.24)
dp-851
What problems should SEOER pay attention to when baidu searches and attacks pirated websites?
AI model risk assessment Part 1: motivation
Sunfeng, general manager of Yixun: the company has completed the share reform and is preparing for IPO
einsum(): operands do not broadcast with remapped shapes [original->remapped]: [1, 144, 20, 17]->[1,