反转整数 c语言,每日LeetCode - 7. 整数反转(C语言和Python 3)

本文探讨了如何在C语言和Python中不使用long类型限制,通过巧妙算法实现整数反转,特别关注31位边界处理。作者分享了C语言和Python代码示例,并讨论了pow和边界检查的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

99c4fcab5367345e6f277d631375285c.png

C语言

使用long类型:

#include "math.h"

int reverse(int x){

int max = pow(2,31)-1;

int min = pow(2,31)*-1;

long n=0;

while (x!=0){

n = n*10 + x%10;

x = x/10;

}

if (n>=min && n <= max)

return n;

else

return 0;

}

只使用int,不使用long类型:

#include "math.h"

int reverse(int x){

int max = pow(2,31)-1;

int min = pow(2,31)*-1;

int n=0;

while (x!=0){

if (n>max/10 || n

return 0;

}

else{

n = n*10 + x%10;

x = x/10;

}

}

return n;

}

Python 3

class Solution:

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

n=0

while x!=0:

n=n*10+x%10

x=x/10

return n if n!=None else 0

标签:10,min,Python,pow,31,long,C语言,int,LeetCode

来源: https://www.cnblogs.com/vicky2021/p/14727858.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值