Determines whether an integer is a square number

Source: Internet
Author: User

367. Valid Perfect Square

Test instructions: Do not use the API to determine whether an integer is a square number.

The idea of starting is to determine whether the square number is directly in the dichotomy.

The wrong code:

1  Public BooleanIsperfectsquare (intnum) {2         //binary Search3         intI=0;4         intn=num;5          while(i<=N) {6             intmid=i+ (n-i)/2;7             intsquare=mid*mid;8             if(Square==num)return true;9             Else if(square<num) {TenI=mid+1; One             } A             Else { -N=mid-1; -             } the         } -         return false; -}

The multiplication of the 7th row overflows and the test times out (it should be that the overflow causes the loop to run continuously).

Modify the following code to pass the test.

1  Public BooleanIsperfectsquare (intnum) {2         //binary Search3         intI=1;4         intN= (num>>1) +1;5          while(i<=N) {6             intmid=i+ (n-i)/2;7             LongSquare= (Long) mid*mid;8             if(square== (Long) num)return true;9             Else if(square< (Long) num) {TenI=mid+1; One             } A             Else { -N=mid-1; -             } the         } -         return false; -}

Determines whether an integer is a square number

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: 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.