Checking Prime Number
public boolean isPrime(int N) {
if (N < 2) return false;
int R = (int) Math.sqrt(N);
for (int d = 2; d <= R; ++d)
if (N % d == 0) return false;
return true;
}ReverseNumber
While(num>newNum)
{
int temp = num%10;
newNum = newNum*10+temp;
num=num/10;
}
if(num == newNum || num ==newNum/10)
return true;
else
return falseChecking Bits set in Unsigned Integer
public int hammingWeight(int n) {
int sum = 0;
while (n != 0) {
sum++;
n &= (n - 1);
}
return sum;
}Check Monotonic Array in One Pass
public boolean isMonotonic(int[] A) {
boolean increasing = true;
boolean decreasing = true;
for (int i = 0; i < A.length - 1; ++i) {
if (A[i] > A[i+1])
increasing = false;
if (A[i] < A[i+1])
decreasing = false;
}return increasing || decreasing; }
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
public int trailingZeroes(int n) {
int r = 0;
while (n > 0) {
n /= 5;
r += n;
}
return r;
}O(log_5(N)) (base 5!) is faster than any polynomial. You need no more than 14 iterations to get the result. You just need to count how many times 5 appears in n! during multiplication in different forms: 5, 25, 125, 625, … . when any 5 is multiplied by 2 (we have many of them) then we get 0 at the end. That’s it.
Representing Matrix Grids in a Unique Way
row * COL_MAX + col
Swapping numbers without using any buffer
a=3 b=2 Method 1: a = a+b; b = a-b; a = a-b; This doesn't if INT overflows
a= a^b; b = a^b; a = a^b;
Checking Integer overflow
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;