Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
先是用了一个 (int) Math.floor(Math.sqrt((double) x));
一分钟拿了个Accepted.
然后花了十几分钟反编译 (A + B)^2 = A2 + 2AB + B2, 写了一个算法,数学逻辑的。carry nextbit等命名有点头晕,调试了十几分钟总算accept了。
public class Solution {
public int sqrt(int x) {
if (x <= 0) {
return 0;
}
String str = String.valueOf(x);
int result = 0;
int carry = 0;
int len = str.length();
for (int i = 0; i < (len + 1) / 2; i++) {
String first2 = str.substring(0, str.length() % 2 == 0 ? 2 : 1);
str = str.substring(first2.length());
int f2 = Integer.valueOf(first2);
int nextBit = 0;
for (int j = 1; j <= 10; j++) {
if ((20 * result + j) * j > carry * 100 + f2) {
nextBit = j - 1;
break;
}
}
carry = carry * 100 + f2 - (result * 20 + nextBit) * nextBit;
result = result * 10 + nextBit;
}
return result;
}
}
public int sqrt(int x) {
if (x <= 0) {
return 0;
}
String str = String.valueOf(x);
int result = 0;
int carry = 0;
int len = str.length();
for (int i = 0; i < (len + 1) / 2; i++) {
String first2 = str.substring(0, str.length() % 2 == 0 ? 2 : 1);
str = str.substring(first2.length());
int f2 = Integer.valueOf(first2);
int nextBit = 0;
for (int j = 1; j <= 10; j++) {
if ((20 * result + j) * j > carry * 100 + f2) {
nextBit = j - 1;
break;
}
}
carry = carry * 100 + f2 - (result * 20 + nextBit) * nextBit;
result = result * 10 + nextBit;
}
return result;
}
}
最后想了想也挺傻的。其实完全可以投机取巧。
重新写了一个5分钟版本。区别其实说起来算法复杂度比那个数学算法还低,但是更多的依赖于Loop
public int sqrt(int x) {
if (x <= 0) {
return 0;
}
String str = String.valueOf(x);
int result = 0;
int len = str.length();
int temp = 0;
for (int i = 0; i < (len + 1) / 2; i++) {
String next2 = str.substring(0, str.length() % 2 == 0 ? 2 : 1);
str = str.substring(next2.length());
int f2 = Integer.valueOf(next2);
temp = temp * 100 + f2;
int nextBit = 0;
for (int j = 1; j <= 10; j++) {
if ((result * 10 + j) * (result * 10 + j) > temp) {
nextBit = j - 1;
break;
}
}
result = result * 10 + nextBit;
}
return result;
}
}