leetCode算法题:7.整数反转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321
 示例 2:

输入: -123
输出: -321
示例 3:

输入: 120
输出: 21
注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

package com.panghl.leetcode.simple;

import java.util.Scanner;

/**
 * @Author panghl
 * @Date 2020/12/9 15:10
 * @Description 整数反转
 **/
public class IntegerReverse {

  public static Integer input() {
    Scanner scanner = new Scanner(System.in);
    Integer nums = scanner.nextInt();
    return nums;
  }

  public static void main(String[] args) {
    Integer num = input();
    int reverse = reverse(num);
    System.out.println(reverse);
  }

  public static int reverse(int num) {
    //记录反转数字
    int ans = 0;

    while (num != 0) {
      //记录个位数
      int pop = num % 10;

      //用于判断反转后的数字是否溢出
      if (ans > Integer.MAX_VALUE/10 || ( ans == Integer.MAX_VALUE/10 && pop > 7)) {
        return 0;
      }

      if (ans < Integer.MIN_VALUE/10 || ( ans == Integer.MIN_VALUE/10 && pop < -8)) {
        return 0;
      }
      ans = ans * 10 + pop;
      num /= 10 ;
    }
    return ans;

  }
}

猜你喜欢

转载自blog.csdn.net/qq_45441466/article/details/110928105