Plus One - Leet Code Solution
Problem Statement Given a non-empty array of digits representing a non-negative…
August 27, 2019
Given a signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Return 0 for Integer overflow
The algorithm should be simple. You fetch the last digit. For next round, you need to move this to next digit place, and add next last digit.
s = s*10 + remainder;
You need to take care of the integer overflow.
We will do two calculations
Overflow cases
:
Note, max limit for 64-bit integer: 2^(64-1) - 1 = 2147483647
case 1
: Multiplication is itself overflowed:
Operation we will do: s10, we can check if s10 > Integer.MAX_VALUE
OR, s > Integer.MAX_VALUE/10
case 2
: if s*10 is equal to Integer.MAX_VALUE, Which means the number will be 214748364
multiply it with 10 will give: 21474836470
So, we need to check the remainder (which is to be added), if it is greater than 7, it is an overflow.
public class Q7_ReverseInteger {
public int reverse(int x) {
boolean neg = false;
if (x < 0) {
//negative number
neg = true;
x = -x;
}
int s = 0;
while (x > 0) {
int rem = x%10;
if (s > Integer.MAX_VALUE/10 || (s == Integer.MAX_VALUE/10 && rem > 7)) {
return 0;
}
s = s*10 + rem;
x = x/10;
}
if (neg) {
return -s;
}
return s;
}
}
It is equal to the number of digits of the number. O(l)
Problem Statement Given a non-empty array of digits representing a non-negative…
Problem Statement Replace all spaces in a string with ‘%20’ (three characters…
Problem Statement You are given a rows x cols matrix grid. Initially, you are…
Problem Statement Maximum Length of Subarray With Positive Product. Given an…
Problem Statement Given a Binary tree, print out nodes in level order traversal…
Problem Statement Roman numerals are represented by seven different symbols: I…
Introduction In this post we will see following: How to schedule a job on cron…
Introduction There are some cases, where I need another git repository while…
Introduction In this post, we will see how to fetch multiple credentials and…
Introduction I have an automation script, that I want to run on different…
Introduction I had to write a CICD system for one of our project. I had to…
Introduction Java log4j has many ways to initialize and append the desired…