General Flashcards

1
Q

Checking Prime Number

A
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;
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

ReverseNumber

A
While(num>newNum)
{
int temp = num%10;
newNum = newNum*10+temp;
num=num/10;
}
if(num == newNum || num ==newNum/10)
     return true;
else
     return false
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Checking Bits set in Unsigned Integer

A
public int hammingWeight(int n) {
    int sum = 0;
    while (n != 0) {
        sum++;
        n &amp;= (n - 1);
    }
    return sum;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Check Monotonic Array in One Pass

A
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;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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.

A
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Representing Matrix Grids in a Unique Way

A

row * COL_MAX + col

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Swapping numbers without using any buffer

A
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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Checking Integer overflow

A

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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly