Add Digits

★☆☆☆☆

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Do it without any loop/recursion in O(1) runtime?

//or simply: return (num - 1) % 9 + 1;
public int addDigits(int num) {
    if (num == 0) return num;
    return (num % 9 != 0)? num % 9: 9;
}

Power of Three

★☆☆☆☆

Given an integer, write a function to determine if it is a power of three. Do it without using any loop / recursion!

public boolean isPowerOfThree(int n) {
    return n > 0 && 1162261467 % n == 0;
}

results matching ""

    No results matching ""