LeetCode in Kotlin

633. Sum of Square Numbers

Medium

Given a non-negative integer c, decide whether there’re two integers a and b such that a2 + b2 = c.

Example 1:

Input: c = 5

Output: true

Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: c = 3

Output: false

Constraints:

Solution

import kotlin.math.sqrt

class Solution {
    fun judgeSquareSum(c: Int): Boolean {
        val right = sqrt(c.toDouble()).toInt()
        val left = sqrt(c.toDouble() / 2).toInt()
        for (i in left..right) {
            val j = sqrt(c - (i * i).toDouble()).toInt()
            if (i * i + j * j == c) {
                return true
            }
        }
        return false
    }
}