C++ 0069.cpp
class Solution {
public:
int mySqrt(int x) {
int64_t step = 1 << 16;
int guess = 0;
while (step > 0)
{
if ((guess + step) * (guess + step) <= x)
guess += step;
step >>= 1;
}
return guess;
}
};
Difficulty
and has an acceptance rate of about 42% (7+ million submissions).
Typical patterns to solve this problem:
- Binary Search
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The function implements an integer square-root calculation for a non-negative 32-bit integer x. It returns the greatest integer guess such that guess * guess does not exceed x. The algorithm follows a deterministic binary-search-like process that works entirely with integer arithmetic and avoids floating-point operations.
Key Steps
Initialization
int64_t step = 1 << 16;
int guess = 0;
The variable step is seeded with 2^16 (65536). This value is larger than the maximum possible integer square root for a 32-bit signed integer (46340), guaranteeing that the first comparison will always be safe. guess starts at zero and will be incrementally built up to the final result.
Iterative Refinement Loop
while (step > 0)
{
if ((guess + step) * (guess + step) <= x)
guess += step;
step >>= 1;
}
The loop runs while step remains positive. In each iteration the algorithm tests whether adding the current step to guess would keep the square within the bound x. If the test succeeds, step is added to guess. Regardless of the test outcome, step is halved by a right-shift, preparing the next finer granularity. This pattern mirrors a binary search on the possible square-root values, narrowing the search space by powers of two.
Return
return guess;
After the loop finishes, guess holds the integer square root and is returned to the caller.
Edge Cases Handled
When x is zero, the condition (guess + step) * (guess + step) <= x never becomes true because any positive step would produce a positive square. Consequently guess stays at zero and the function returns zero, which is the correct square root.
For x equal to one, the first iteration where step is 65536 fails the test, but as step halves repeatedly, the condition becomes true when step reaches one. At that point guess is incremented to one, and the loop continues with step becoming zero, yielding the correct result.
The algorithm also correctly processes the maximum 32-bit signed integer (INT_MAX). The multiplication (guess + step) * (guess + step) is performed in 64-bit arithmetic because step is a 64-bit value, preventing overflow even when the intermediate square exceeds the 32-bit range. The comparison against x remains valid because x is promoted to 64-bit for the comparison.
Performance Optimizations
The implementation achieves a fixed number of iterations equal to the number of bits in the initial step value (16). Each iteration performs a single multiplication and a comparison, both of which are inexpensive integer operations. By starting with a power-of-two step that exceeds any possible result, the algorithm eliminates the need for dynamic bounds calculation and reduces branching overhead.
Using bitwise shift operators (<< and >>) for scaling step is faster than arithmetic multiplication or division. The entire method runs in deterministic time, independent of the magnitude of x, which is advantageous for real-time or embedded contexts where predictable execution time is required.
ELI5 - Simplified Explanation
Imagine you are trying to guess a secret number that, when multiplied by itself, is as close as possible to a big number like one hundred. To find the answer, you start with a big jump called a step. You check if adding that step to your guess makes the result too big. If the result is still smaller than or equal to the big number, you keep that step and add it to your total. Then, you make the step half as small as it was before. You keep doing this over and over again, taking smaller and smaller steps, until you get exactly to the number you are looking for. It is just like playing a game of hot and cold where you constantly narrow down where the answer is hiding. Once the steps get so tiny that they disappear, you know you have found the biggest possible number that stays under or hits your target.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | C# | Rust | JS | Go | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| bujosa | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| pruthvikp | Python | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| bujosa | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| Dijkstra-Edu | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| pruthvikp | Python | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 50: Pow(x, n)
- problem 367: Valid Perfect Square
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality