Genius ask the Java problem question in Typescript relate server

I currently learning JAVA, so i rewriting my old JS algorithm from leetcode to practice JAVA. the problem is this code right below make "Time Limit Exceeded" error.
class Solution {
public int mySqrt(int x) {
long left = 0;
long right = x;
while(left <= right){
long mid = left + (right - left) / 2;
long doub = mid * mid;
if(doub == x){
return (int) mid;
}
if(doub > x){
left = mid - 1;
}
if(doub < x){
right = mid + 1;
}
}
return (int) right;
}
}
class Solution {
public int mySqrt(int x) {
long left = 0;
long right = x;
while(left <= right){
long mid = left + (right - left) / 2;
long doub = mid * mid;
if(doub == x){
return (int) mid;
}
if(doub > x){
left = mid - 1;
}
if(doub < x){
right = mid + 1;
}
}
return (int) right;
}
}
but when you use same code but update else if else instead of just if guards it works fine.
class Solution {
public int mySqrt(int x) {
long left = 0;
long right = x;

while (left <= right) {
long mid = left + (right - left) / 2;
long doub = mid * mid;

if (doub == x) {
return (int) mid;
} else if (doub > x) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return (int) right;
}
}
class Solution {
public int mySqrt(int x) {
long left = 0;
long right = x;

while (left <= right) {
long mid = left + (right - left) / 2;
long doub = mid * mid;

if (doub == x) {
return (int) mid;
} else if (doub > x) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return (int) right;
}
}
i really can not understand why, because i tried to add "continue" at the end of every if statement and the same error occur when is should skip in that logic cicle. Thanks in advance
4 Replies
Keef
Keef12mo ago
Probably some compiler optimization is being lost when you do the separate three ifs versus the one control flow That’s why you see that issue
Vincent Udén
Vincent Udén12mo ago
And just to add to the discussion if -> continue will almost certainly result in more bytecode (and worse perf) than if -> else if since the JVM will have to find what is needing to be continued since it hypothetically could be inside nested loops
choco
chocoOP12mo ago
thanks guys @keef (Rustular CVO) @Vincent I thought at first maybe i am doing something really wrong. Also i really like Java, when i created C# backend i was really regretting it. But Java is cool.
Keef
Keef12mo ago
Yeah I was guessing this too. nice to see it was the right idea
Want results from more Discord servers?
Add your server