Given a positive integer num, write a function that returns True if num is a perfect square else False.
Example 1:
Input: num = 16
Output: true
Approach
Java
public class ValidPerfectSquare {public static void main(String[] args) {int num = 16;System.out.println(isPerfectSquare(num));}static public boolean isPerfectSquare(int x) {if (x <= 1)return true;long low = 1l;long high = x / 2;long mid = 0l;while (low <= high) {mid = low + (high - low) / 2;if (mid * mid < x) {low = low + 1;} else if (mid * mid > x) {high = mid - 1;} elsereturn true;}return false;}}
C++
#include <bits/stdc++.h>using namespace std;bool isPerfectSquare(int num){for (int i = 1; (long long int)i * i <= num; i++){if ((float)num / i == i){return true;}}return false;}int main(){int num = 16;if (isPerfectSquare(num))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment