7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
import java.util.*;
public class Solution {
public static int reverse(int x) {
long reverse_x = 0;
while(x != 0){
reverse_x = reverse_x * 10;
int a = x % 10;
int b = x / 10;
x = b;
reverse_x += a;
}
if (reverse_x > Integer.MAX_VALUE || reverse_x < Integer.MIN_VALUE){
reverse_x = 0;
}
return (int)reverse_x;
}
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
try{
int x = reader.nextInt();
int reverse_x = reverse(x);
System.out.print(reverse_x);
}catch(InputMismatchException e){
System.out.print("0");
}
}
}
参考:https://www.kyledong.com/leetcode-reverse-integer/
9. Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
import java.util.*;
public class Solution {
public static boolean isPalindrome(int x) {
long reverse_x = 0;
int input_x = x;
while(x > 0){
reverse_x *= 10;
int a = x % 10;
int b = x / 10;
x = b;
reverse_x += a;
}
if (reverse_x == input_x){
return true;
}else{
return false;
}
}
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
try{
int x = reader.nextInt();
if(x >= 0){
System.out.print(isPalindrome(x));
}else{
System.out.print(false);
}
}catch(InputMismatchException e){
System.out.print(0);
}
}
}