LeetCode-in-Java

3918. Sum of Primes Between Number and Its Reverse

Medium

You are given an integer n.

Let r be the integer formed by reversing the digits of n.

Return the sum of all prime numbers between min(n, r) and max(n, r), inclusive.

Example 1:

Input: n = 13

Output: 132

Explanation:

Example 2:

Input: n = 10

Output: 17

Explanation:

Example 3:

Input: n = 8

Output: 0

Explanation:

Constraints:

Solution

public class Solution {
    private boolean isPrime(int x) {
        if (x <= 1) {
            return false;
        }
        if (x == 2) {
            return true;
        }
        if (x % 2 == 0) {
            return false;
        }
        for (int i = 3; i * i <= x; i += 2) {
            if (x % i == 0) {
                return false;
            }
        }
        return true;
    }

    private int reverseNum(int n) {
        int r = 0;
        while (n > 0) {
            r = r * 10 + (n % 10);
            n /= 10;
        }
        return r;
    }

    public int sumOfPrimesInRange(int n) {
        int r = reverseNum(n);
        int low = Math.min(n, r);
        int high = Math.max(n, r);
        int sum = 0;
        for (int i = low; i <= high; i++) {
            if (isPrime(i)) {
                sum += i;
            }
        }
        return sum;
    }
}