package javaLeetCode_primary;
import java.util.Scanner;
/**
* Given a 32-bit signed integer, reverse digits of an integer. <b>Example 1:
* <li>Input: 123
* <li>Output: 321 Example 2:
* <li>Input: -123
* <li>Output: -32 Example 3:
* <li>Input: 120
* <li>Output: 21
*/
/*
* Test data:
*1534236469->0
*999999991->199999999
*2147483647->0
*2147483642 ->0
*1000000000->1
*-2147483648->0
*-214748364->-463847412
*901000-> 109
*/
public class ReverseInteger_7 {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Please input a integer:");
int x = input.nextInt();
System.out.println(reverse_2(x));
}// end main
/**
* Use simple methods to solve problems.
*/
public static int reverse_1(int x) {
int[] arr = new int[10];// Stores the number of bits of a parameter
int countDigit = 0;// Calculate the length of the number
int cf = 0;// Leave the parameter state
int i = 0;
// The element that initializes array is 0.
for (i = 0; i < arr.length; i++) {
arr[i] = 0;
} // end for
if (x < 0) {
cf = 1;
x *= -1;
} // end if
//Get the the digit of parameter and reverse/invert it.
i = 0;
while (x > 0) {
countDigit++;
arr[i] = x % 10;
x /= 10;
i++;
} // end while
// Print the integer
i = 0;
long y = 0;
for (; i < countDigit; i++) {
y = y * 10 + arr[i];
} // end for
//Judge whether the integer is valid.
if(y>2147483647) {
x = 0;
}else {
x = (int)y;
}//end if
if (cf == 1) {
x *= -1;
} // end if
return x;
}// end reverse()
/**
* Answer online
* */
public static int reverse_2(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}//end reverse()
}
Java实现LeetCode_0007_ReverseInteger
2023-09-14 08:58:08 时间
相关文章
- Java实现 LeetCode 792 自定义字符串排序(暴力)
- Java实现 LeetCode 756 金字塔转换矩阵(DFS)
- Java实现 LeetCode 674 最长连续递增序列(暴力)
- Java实现 LeetCode 639解码方法 2(递推)
- Java实现 LeetCode 629 K个逆序对数组(动态规划+数学)
- Java实现 LeetCode 563 二叉树的坡度(又是一个遍历树)
- Java实现 LeetCode 547 朋友圈(并查集?)
- Java实现 LeetCode 535 TinyURL 的加密与解密(位运算加密)
- Java实现 LeetCode 508 出现次数最多的子树元素和
- Java实现 LeetCode 494 目标和
- Java实现 LeetCode 496 下一个更大元素 I
- Java实现 LeetCode 482 密钥格式化
- Java实现 LeetCode 1两数之和
- Java实现 LeetCode 462 最少移动次数使数组元素相等 II
- Java实现 LeetCode 424 替换后的最长重复字符
- Java实现 LeetCode 413 等差数列划分
- Java实现 LeetCode 357 计算各个位数不同的数字个数
- Java实现 LeetCode 330 按要求补齐数组
- Java实现 LeetCode 295 数据流的中位数
- Java实现 LeetCode 278 第一个错误的版本
- Java实现 LeetCode 203 移除链表元素
- Java实现 LeetCode 112 路径总和
- Java实现 LeetCode 38 外观数列
- Java实现 LeetCode 14 最长公共前缀
- Java实现 LeetCode 11 盛最多水的容器
- 在Java中可以使用自定义的java.net.InetAddress实现来解决虚拟hosts的问题