Skip to main content

Command Palette

Search for a command to run...

Sqrt(x)

Published
1 min read
Sqrt(x)
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

LeetCode Problem - 69

class Solution {
    public int mySqrt(int x) {
        // Call the helper function 'findSquareRoot' to compute the square root of 'x' as a double
        double squareRoot = findSquareRoot((double) x);

        // Return the integer part of the square root by casting the result to 'int'
        return (int) squareRoot;
    }

    // Helper method to calculate the square root using Newton's method (approximation technique)
    public double findSquareRoot(double number){
        // Initial guess for the square root
        double guess = 1;

        // Tolerance value (epsilon) to control the accuracy of the result
        double epsilon = 0.00001;

        // Iteratively adjust the guess until the difference between guess^2 and 'number' is within the tolerance (epsilon)
        while (Math.abs(guess * guess - number) >= epsilon) {
            // Update guess using Newton's method formula: (guess + number / guess) / 2
            guess = (guess + number / guess) / 2;
        }

        // Return the final guess, which is the approximate square root of 'number'
        return guess;
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.