1.整数反转


给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。 如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。 环境不允许存储 64 位整数(有符号或无符号)。 leetcode 7

  1. 输入:x = 120 输入:x = -123
  2. 输出:21 输出:-321

取余除10,不断缩小

  1. -4444 % 10 = -4 正数负数的终止条件一致
  2. 当达到最大值的1/10时,就要提前判断,是否溢出;同理,到最小值的1/10时也要提前判断防溢出。
  3. 溢出情况j简化考虑:因为x本身会被int限制,当x为正数并且位数和Integer.MAX_VALUE的位数相等时首位最大只能为2,所以逆转后不会出现res = Integer.MAX_VALUE / 10 && tmp > 2的情况,自然也不需要判断res==214748364 && tmp>7了,反之负数情况也一样

image.pngimage.png

  1. class Solution {
  2. public int reverse(int x) {
  3. int res = 0;
  4. while(x != 0){
  5. int tmp = x % 10;
  6. if (res > Integer.MAX_VALUE / 10 || res < Integer.MIN_VALUE / 10) {
  7. return 0;
  8. }
  9. //判断是否 大于 最大32位整数
  10. //if (res>214748364 || (res==214748364 && tmp>7)) {
  11. // return 0;
  12. //}
  13. //判断是否 小于 最小32位整数
  14. //if (res<-214748364 || (res==-214748364 && tmp<-8)) {
  15. // return 0;
  16. //}
  17. res = res * 10 + tmp;
  18. x /= 10;
  19. }
  20. return res;
  21. }
  22. }

2.回文整数


给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。 leetcode 9

字符串反转(略)

对半反转整数

  1. 结束条件:res > x
  2. 判断条件:res == x(偶数位情况) x == res / 10 (奇数位情况) 121 -> res :12 x :1

    1. class Solution {
    2. public boolean isPalindrome(int x) {
    3. if(x < 0 || x % 10 == 0 && x != 0) return false;
    4. int res = 0;
    5. while(x > res){
    6. res = res * 10 + x % 10;
    7. x /= 10;
    8. }
    9. return res == x || x == res / 10;
    10. }
    11. }

    拆出最高位和最低位比较

    1. public boolean isPalindrome(int x) {
    2. //边界判断
    3. if (x < 0) return false;
    4. int div = 1;
    5. //
    6. while (x / div >= 10) div *= 10; // 求出位数
    7. while (x > 0) {
    8. int left = x / div;
    9. int right = x % 10;
    10. if (left != right) return false;
    11. x = (x % div) / 10;
    12. div /= 100; // 两位两位的缩减规模
    13. }
    14. return true;
    15. }

    3.字符串转整数


实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的 atoi 函数)。考虑溢出情况 leetcode 8

溢出判断:last != res / 10

更新res 后计算后立即判断,否则跨循环判断 idx可能溢出,导致返回错误的res结果

  1. public int myAtoi(String s) {
  2. char[] chars = s.toCharArray();
  3. int len = chars.length;
  4. //1.去空格
  5. int index = 0;
  6. while (index < len && chars[index] == ' ')
  7. index++;
  8. //2.排除极端情况 " "
  9. if (index == len) return 0;
  10. //3.设置符号
  11. int sign = 1;
  12. char firstChar = chars[index];
  13. if (firstChar == '-') {
  14. index++;
  15. sign = -1;
  16. } else if (firstChar == '+') {
  17. index++;
  18. }
  19. int res = 0, last = 0; //last 记录上一次的res,以此来判断是否溢出
  20. while (index < len) {
  21. char c = chars[index];
  22. if (c < '0' || c > '9') break;
  23. int tem = c - '0';
  24. last = res;
  25. res = res * 10 + tem;
  26. // 计算后立即判断,否则idx可能溢出,导致返回错误的res结果
  27. if (last != res / 10) ////如果不相等就是溢出了
  28. return (sign == (-1)) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
  29. index++;
  30. }
  31. return res * sign;
  32. }