367. Valid Perfect Square Java Solutions

Source: Internet
Author: User

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note:do no built-in library function such as sqrt .

Example 1:

Input:16returns:true

Example 2:

Input:14returns:false

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Solution One:
1  Public classSolution {2      Public BooleanIsperfectsquare (intnum) {3         if(Num < 0)return false;4         if(num = = 1)return true;5          for(inti = 1; i<= num/i;i++){6             if(i*i = = num)return true;7         }8         return false;9     }Ten}

Solution 2: Binary Lookup method (Java without AC for reference only)

1  Public classSolution {2      Public BooleanIsperfectsquare (intnum) {3         if(Num < 0)return false;4         if(num = = 1)return true;5         intLow = 0, high = NUM/2;6          while(Low <=High ) {7             LongMid = (low + high)/2;8             LongTMP = mid*mid;9             if(tmp = = num)return true;Ten             if(tmp > num) high = Mid-1; One             ElseLow = mid + 1; A         } -         return false; -     } the}

The solution 3:https://leetcode.com/discuss/110659/o-1-time-c-solution-inspired-by-q_rsqrt the O (1) Solution of the Great God.

Solution 4:

The total number of squares is a series of odd sum, for example:

1 = 1
4 = 1 + 3
9 = 1 + 3 + 5
16 = 1 + 3 + 5 + 7
25 = 1 + 3 + 5 + 7 + 9
36 = 1 + 3 + 5 + 7 + 9 + 11
....
1+3+...+ (2n-1) = (2n-1 + 1)N/2 =n

1  Public classSolution {2      Public BooleanIsperfectsquare (intnum) {3         inti = 1;4          while(num > 0) {5num-=i;6i + = 2;7         }8         returnnum = = 0;9     }Ten}

367. Valid Perfect Square Java Solutions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.