【LeetCode练习】[简单]7. 整数反转

it2026-04-24  3

【LeetCode练习】[简单]7. 整数反转

7. 整数反转

题目来源 算法思想:编程中 % / 的利用

题目:利用long来判断溢出情况 注意:溢出的情况,分为正数的溢出以及负数的溢出;

java代码

class Solution { public int reverse(int x) { int tmp = 0; Long res = 0L;//用来存放结果,用int溢出的时候不好判断 while(x != 0) { tmp = x % 10;//提取x的个位数 //判断是否溢出 if (res * 10 > Integer.MAX_VALUE || res * 10 + tmp > Integer.MAX_VALUE || res * 10 < Integer.MIN_VALUE || res * 10 + tmp < Integer.MIN_VALUE ){ return 0;//如果溢出一直返回0 } res = res * 10 + tmp;//存入值 x = x / 10;//x去掉个位数 } return res.intValue();//返回int范围内的值 } }

java代码–存放结果不用long

class Solution { public int reverse(int x) { int tmp = 0; int res = 0;//用来存放结果,用int溢出的时候不好判断 while(x != 0) { tmp = x % 10;//提取x的个位数 int newRes = res * 10 + tmp;//存入值 //判断是否溢出 if (newRes / 10 != res){//除以10判断是否越界,不用long return 0;//如果溢出一直返回0 } res = newRes; x = x / 10;//x去掉个位数 } return res;//返回int范围内的值 } }
最新回复(0)