Find the maximum sum of any continuous subarray of size K
Introduction You are given an array of integers with size N, and a number K…
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.
You need to get last digit from number, and multiply last result by 10 to move it to next place.
s = s*10 + remainder;
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.MAXVALUE
OR, s > Integer.MAXVALUE/10case 2
: if s10 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)
Introduction You are given an array of integers with size N, and a number K…
Problem Statement Given a non-empty array of digits representing a non-negative…
Here are some tips while giving your coding interviews. 1. Never try to jump to…
Problem Statement Given an array of integers, find if the array contains any…
Problem Statement Given an array nums of n integers, are there elements a, b, c…
Min Priority Queue is a data structure which manage a list of keys(values). And…
In this post, we will see some of the frequently used concepts/vocabulary in…
System design interview is pretty common these days, specially if you are having…
Introduction You are given an array of integers with size N, and a number K…
Graph Topological Sorting This is a well known problem in graph world…
Problem Statement Given a Binary tree, print out nodes in level order traversal…
Problem Statement Given an array nums of n integers and an integer target, are…