求平方根的算法题,输入4输出2, 输入8也输出2(去掉小数点后)

我想先尝试最简单的,这是我的代码
1. class Solution {
1. public int mySqrt(int x) {
1. int i = 0, j = 0;
1. while(j < x){
1. j = i * i ;
1. if((i+1)*(i+1)<x)i++;
1. }
1. return i;
1. }
1. }
1.
但是运行的时候超时了,我就想知道为什么会超时

if((i+1)*(i+1)<x)i++; else break;

因为你的循环一直出不去,在你的while循环里,j永远都会小于x,原因就是你的if导致的。你的逻辑倒是挺神奇的
while(i * i <= x) i++;
return i -1;
不就可以了吗