Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Here, We are using String and StringBuilder concepts.
1)Convert int to string.
2)If it 0 , just return it.
3)If it is less than 0, separate '-' and number. Insert number string to StringBuilder and do the reverse. Finally merge both substring.
4)If it is greater than 0, insert number string to StringBuilder and do the reverse. Finally merge both substring.
5)After that check starting of number whether it contains 0 or not. If it contains 0 traverse till digit greater than 0 and using that 'i' position separate 0's from number.
6)Finally check the condition,
If returning number is greater than Integer Max value or lesser than Integer Min Value it must be 0 (condition given in the question)
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
class Solution {
public int reverse(int x) {
StringBuilder sb;
String str = x+"";
int i;
if(x==0)
return 0;
if(x<0){
String sub1 = str.substring(0,1);
String sub2 = str.substring(1);
sb = new StringBuilder(sub2);
sb.reverse();
str = sub1+sb.toString();
}
else{
sb = new StringBuilder(str);
sb.reverse();
str = sb.toString();
for( i=0;i<str.length();i++){
if(str.charAt(i)!=0){
break;
}
}
str = str.substring(i);
}
if (Long.parseLong(str) > Integer.MAX_VALUE || Long.parseLong(str) < Integer.MIN_VALUE){
return 0;
}
else{
return Integer.parseInt(str);
}
}
}
Here, We are using String and StringBuilder concepts.
1)Convert int to string.
2)If it 0 , just return it.
3)If it is less than 0, separate '-' and number. Insert number string to StringBuilder and do the reverse. Finally merge both substring.
4)If it is greater than 0, insert number string to StringBuilder and do the reverse. Finally merge both substring.
5)After that check starting of number whether it contains 0 or not. If it contains 0 traverse till digit greater than 0 and using that 'i' position separate 0's from number.
6)Finally check the condition,
If returning number is greater than Integer Max value or lesser than Integer Min Value it must be 0 (condition given in the question)
Comments
Post a Comment