LeetCode 125: Palindrome Number Easy Leetcode [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is my answer. However, I couldn't pass the test case for "11".
I couldn't find what is wrong in the code. Please help! Thank you!
/**
* #param {number} x
* #return {boolean}
*/
var isPalindrome = function(x) {
if (x === 0) {
return true;
}
if (x < 0 || x % 10 === 0) {
return false;
}
let rev = 0;
while (x > rev) {
pop = x % 10;
x = x / 10;
rev = (rev * 10) + pop;
}
if (x === rev || x === rev / 10) {
return true;
}
else {
return false;
}
};

Finding palindromes is inherently something which you would typically do using strings, not numeric variables, so I suggest converting your number to a string, and going from there:
var isPalindrome = function(x) {
x = x + ""; // convert to string, if x be a number
var isPalindrome = true;
for (i = 0; i < x.length/2; i++) {
if (x.substring(i, i+1) != x.substring(x.length-1-i, x.length-i)) {
isPalindrome = false;
break;
}
}
return isPalindrome;
}
console.log(isPalindrome(1234321));
console.log(isPalindrome(1234329));
The strategy here is just to iterate half the string, and assert that each character matches its counterpart in the other half. Note that we don't need to check the middle character, in the case of an input with an odd number of characters.

Your question seems to be LeetCode 9 and in the discussion board, there are good accepted solutions such as:
JavaScript
var isPalindrome = function(x) {
if (x < 0)
return false;
let reversed = 0;
for (let i = x; i > 0; i = Math.floor(i / 10))
reversed = reversed * 10 + i % 10;
return reversed === x;
};
Python
class Solution:
def isPalindrome(self, x):
if x < 0 or (x > 0 and not x % 10):
return False
return str(x) == str(x)[::-1]
Java
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0))
return false;
int reversed = 0;
while (x > reversed) {
reversed = reversed * 10 + x % 10;
x /= 10;
}
return (x == reversed || x == reversed / 10);
}
}
There is another similar isPalindrome question that if you might be interested, I've just copied below:
JavaScript I
var isPalindrome = function(s) {
var original = s.replace(/\W/g, ''); // means NON-WORD characters
var reversed = original.split('').reverse().join('');
return original.toLowerCase() == reversed.toLowerCase();
};
JavaScript II
var isPalindrome = function(s) {
var original = s.replace(/[^a-z0-9]/isg, '');
var reversed = original.split('').reverse().join('');
return original.toLowerCase() == reversed.toLowerCase();
};
Java
class Solution {
public boolean isPalindrome(String s) {
String original = s.replaceAll("(?i)[^a-z0-9]", "").toLowerCase();
String reversed = new StringBuffer(original).reverse().toString();
return original.equals(reversed);
}
}
Python
class Solution:
def isPalindrome(self, s):
s = ''.join(re.findall(r'(?is)[a-z0-9]+', s)).lower()
return s == s[::-1]
\W (non-word-character) matches any single character that doesn't match by \w (same as [^a-zA-Z0-9_]).
Reference
You can find additional explanations in the following links:
LeetCode 9 JavaScript Discussion Board
LeetCode 125 JavaScript Discussion Board

Using string for checking palindrome is very easy and straight forward. Having said that if you want to see how you can do it without changing number to string,
First initialise an variable start with Math.pow(10, digit count-1)
Loop till the value of start is greater than 0
inside loop compare the first and last digit if they are not equal return false
on each iteration remove the first and last digit from x and reduce start by 100
var isPalindrome = function(x) {
// as per question on leetcode negative values cannot be palindrome
if( x < 0) {
return false
}
x = Math.abs(x)
// to get the digits from start we need to get log10 of given value
let len = Math.ceil( Math.max( Math.log10(x), 1 ) ) - 1
let start = Math.pow(10, len)
while(start){
// compare first digit with the last digit
if(Math.floor(x/start) != (x % 10)){
return false
}
// remove first digit of current x
x = x % start
// remove last digit of current x
x = Math.floor(x/10)
// reduce start by 100 as we removed 2 digits
start = Math.floor(start / 100)
}
return true
};
console.log(isPalindrome(1))
console.log(isPalindrome(1221))
console.log(isPalindrome(-121))
console.log(isPalindrome(12341))
console.log(isPalindrome(100111))
Note:- We do (digit count - 1) so that we can capture the first digit
Original leetcode question link

Related

Optimizing and finding edge cases that I might have missed - 2 coding interview questions

Background - I took an online coding test and was presented with questions similar to this, I did rather poorly on it compared to the hidden grading criteria and I was hoping to get another pair of eyes to look at it and maybe help point out some of my mistakes.
Practice Test questions -
Task: Given an integer inject the number 5 into it to make the largest possible integer
Conditions: (-80000...80000) range needed to handle
Expected input: int
Expected output: int
Testcase: -999 -> -5999
80 -> 850
var lrgInt = function(num) {
var stringInt = num.toString();
for (let i = 0; i < stringInt.length; i++) {
if (stringInt.charAt(i) === "-") {
return parseInt([stringInt.slice(0, 1), '5', stringInt.slice(1)].join(''));
}else if (stringInt.charAt(i) < 5) {
return parseInt([stringInt.slice(0, i), '5', stringInt.slice(i)].join(''));
}
}
return parseInt([stringInt.slice(0, stringInt.length), '5', stringInt.slice(stringInt.length)].join(''));
};
Task: Determine the number of operations done on a number following the conditions to reduce it to 0.
Conditions:
- If the number is odd, subtract 1
- If the number is even, divide by 2
Expected input: int
Expected output: int
var operations = 0;
var numberOfSteps = function(num) {
if (num === 0){
return operations;
}else if (num % 2 == 0) {
operations++;
return numberOfSteps(num/2);
} else {
operations++;
return numberOfSteps(num-1);
}
};
For the second question, you could add one plus the result of recursion with the adjusted number without having a global counter.
function numberOfSteps(number) {
if (!number) return 0;
if (number % 2) return 1 + numberOfSteps(number - 1);
return 1 + numberOfSteps(number / 2);
}
console.log(numberOfSteps(5)); // 5 4 2 1 0
For the first question, we make the observation that if the number is positive, we want to inject the 5 before the first digit less than 5, but if it's negative then we want to inject it before the first digit greater than 5. For the second problem, we can just use a simple while loop.
function largestNum(num) {
if (num == 0) {
// this edge case is weird but I'm assuming this is what they want
return 50;
}
var negative = num < 0;
var numAsStr = Math.abs(num).toString();
var inj = -1;
for (var i = 0; i < numAsStr.length; i++) {
var cur = parseInt(numAsStr[i], 10);
if ((!negative && cur < 5) || (negative && cur > 5)) {
// we found a place to inject, break
inj = i;
break;
}
}
if (inj == -1) {
// didn't inject anywhere so inject at the end
inj = numAsStr.length;
}
return (
(negative ? -1 : 1) *
parseInt(numAsStr.substr(0, inj) + "5" + numAsStr.substr(inj))
);
}
function numSteps(num) {
var steps = 0;
while (num != 0) {
if (num % 2) {
// it's odd
num--;
} else {
num /= 2;
}
steps++;
}
return steps;
}

How to "round" number, by putting zeros after the 2nd digit in javascript

I would like to "round" an integer number, by swapping all the digits after the 2nd digit to zeros. Additionally, if the number has only 1 digit, then don't do anything, and if the number has 2 digits, then swap the 2nd digit to a 0.
Example:
3 => 3
22 => 20
754 => 750
8912 => 8900
Can this be achieved without truncating the number as a string, and then rebuilding the number with zeros?
You don't need to truncate the number as a string, it can be easily achieved via mathematical calculation. Also, changing number to string and then doing any operation will be an added overhead which is not required in this case.
Refer the code below, it's quite straight forward.
Hope this helps.
function changeNumber(num){
if(Math.floor(num/10) == 0){
return num;
} else if(Math.floor(num/1000) == 0){
return Math.floor(num/10)*10;
}
else{
return Math.floor(num/100)*100
}
}
console.log(changeNumber(3));
console.log(changeNumber(22));
console.log(changeNumber(754));
console.log(changeNumber(8923));
That will work with every base-10 number.
All is about a simple math operation: number - [rest of (number / base-10 of number)]
function round(n) {
if(n < 10) return n;
var d = getTenBase(n.toString().length - 1);
return n - (n % (10 * d));
}
function getTenBase(l) {
var d = 1;
for(var i = 2; i < l; i++) {
d *= 10;
}
return d;
}
console.log(round(3));
console.log(round(22));
console.log(round(768));
console.log(round(1657));
you can just find length and first two character after that take zero with valid length and concat both
var str = '8912';
var n = str.length;
if(n == 1)
{
print(str);
} else if(n==2) {
var strFirst = str.substring(0,1);
var str2 = '0';
var res = strFirst.concat(str2);
} else if(n>2) {
var strFirst = str.substring(0,2);
var i;
var strsec ='0';
for (i = 0; i < n-3; i++) {
strsec += 0 ;
}
var res = strFirst.concat(strsec);
}
print(res);

I need to validate an input string using checksum for alphanumerics

I have the following function that validates a digits input consisted of only numbers based on Luhn Algorithm:
function isCheckdigitCorrect(value) {
// accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) return false;
var nCheck = 0, nDigit = 0, bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
Is there anyway that I can validate also alphanumerics, so let's suppose I have a valid ID: AC813(6) , () is the checksum. So is there a way that I can prevent users having to type mistakenly AF813(6) so this would tell user incorrect ID.
I appreciate your help
Substituting digits for alphabetic characters to calculate a checksum severely reduces the robustness of the check, and the simplest suggestion I can come up with is to use the Luhn mod N algorithm described on Wikipedia.
Translating the algorithm into JavaScipt was relatively straight forward: the following is not my code but a translation from the wiki article - so I won't pretend it is optimal. It is intended to work with strings of case insensitive ASCII alphabetic characters and decimal digits. For documentation see the wiki.
// based on https://en.wikipedia.org/wiki/Luhn_mod_N_algorithm
var charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function NumberOfValidInputCharacters () { return charset.length; }
function CodePointFromCharacter(character) { return charset.indexOf(character)};
function CharacterFromCodePoint( codePoint) { return charset[codePoint]};
function GenerateCheckCharacter (input) {
var factor = 2;
var sum = 0;
var n = NumberOfValidInputCharacters();
input = input.toUpperCase();
// Starting from the right and working leftwards is easier since
// the initial "factor" will always be "2"
for (var i = input.length - 1; i >= 0; i--) {
var codePoint = CodePointFromCharacter(input[i]);
if( codePoint < 0) {
return "";
}
var addend = factor * codePoint;
// Alternate the "factor" that each "codePoint" is multiplied by
factor = (factor == 2) ? 1 : 2;
// Sum the digits of the "addend" as expressed in base "n"
addend = Math.floor(addend / n) + (addend % n);
sum += addend;
}
// Calculate the number that must be added to the "sum"
// to make it divisible by "n"
var remainder = sum % n;
var checkCodePoint = (n - remainder) % n;
return CharacterFromCodePoint(checkCodePoint);
}
function ValidateCheckCharacter(input) {
var factor = 1;
var sum = 0;
var n = NumberOfValidInputCharacters();
input = input.toUpperCase();
// Starting from the right, work leftwards
// Now, the initial "factor" will always be "1"
// since the last character is the check character
for (var i = input.length - 1; i >= 0; i--) {
var codePoint = CodePointFromCharacter(input[i]);
if( codePoint < 0) {
return false;
}
var addend = factor * codePoint;
// Alternate the "factor" that each "codePoint" is multiplied by
factor = (factor == 2) ? 1 : 2;
// Sum the digits of the "addend" as expressed in base "n"
addend = Math.floor(addend / n) + (addend % n);
sum += addend;
}
var remainder = sum % n;
return (remainder == 0);
}
// quick test:
console.log ("check character for 'abcde234': %s",
GenerateCheckCharacter("abcde234"));
console.log( "validate 'abcde2349' : %s " ,
ValidateCheckCharacter( "abcde2349"));
console.log( "validate 'abcde234X' : %s" ,
ValidateCheckCharacter( "abcde234X"));
If you just want to do the Luhn algorithm with letters replacing some of the numbers, then include an additional step to convert letters to numbers within your function.
So if you wanted to allow say A, B, C, D that convert to 0, 1, 2, 3 then you could do:
function isCheckdigitCorrect(value) {
// Letter to number mapping
var letters = {a:'0', b:'1', c:'2', d:'3'};
// Convert letters to their number equivalents, if they have one
value = value.split('').reduce(function(s, c){
return s += letters[c.toLowerCase()] || c;
},'');
// Continue as currently
// accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) return false;
var nCheck = 0, nDigit = 0, bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
// In the following, A = 0 and D = 3
console.log(isCheckdigitCorrect('375767AA4D6AA21'));
You can implement other algorithms in a similar way.

A code wars challenge

I have been struggling with this challenge and can't seem to find where I'm failing at:
Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n. In other words:
Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
If it is the case we will return k, if not return -1.
Note: n, p will always be given as strictly positive integers.
digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
I'm new with javascript so there may be something off with my code but I can't find it. My whole purpose with this was learning javascript properly but now I want to find out what I'm doing wrong.I tried to convert given integer into digits by getting its modulo with 10, and dividing it with 10 using trunc to get rid of decimal parts. I tried to fill the array with these digits with their respective powers. But the test result just says I'm returning only 0.The only thing returning 0 in my code is the first part, but when I tried commenting it out, I was still returning 0.
function digPow(n, p){
// ...
var i;
var sum;
var myArray= new Array();
if(n<0)
{
return 0;
}
var holder;
holder=n;
for(i=n.length-1;i>=0;i--)
{
if(holder<10)
{
myArray[i]=holder;
break;
}
myArray[i]=holder%10;
holder=math.trunc(holder/10);
myArray[i]=math.pow(myArray[i],p+i);
sum=myArray[i]+sum;
}
if(sum%n==0)
{
return sum/n;
}
else
{
return -1;
}}
Here is the another simple solution
function digPow(n, p){
// convert the number into string
let str = String(n);
let add = 0;
// convert string into array using split()
str.split('').forEach(num=>{
add += Math.pow(Number(num) , p);
p++;
});
return (add % n) ? -1 : add/n;
}
let result = digPow(46288, 3);
console.log(result);
Mistakes
There are a few problems with your code. Here are some mistakes you've made.
number.length is invalid. The easiest way to get the length of numbers in JS is by converting it to a string, like this: n.toString().length.
Check this too: Length of Number in JavaScript
the math object should be referenced as Math, not math. (Note the capital M) So math.pow and math.trunc should be Math.pow and Math.trunc.
sum is undefined when the for loop is iterated the first time in sum=myArray[i]+sum;. Using var sum = 0; instead of var sum;.
Fixed Code
I fixed those mistakes and updated your code. Some parts have been removed--such as validating n, (the question states its strictly positive)--and other parts have been rewritten. I did some stylistic changes to make the code more readable as well.
function digPow(n, p){
var sum = 0;
var myArray = [];
var holder = n;
for (var i = n.toString().length-1; i >= 0; i--) {
myArray[i] = holder % 10;
holder = Math.trunc(holder/10);
myArray[i] = Math.pow(myArray[i],p+i);
sum += myArray[i];
}
if(sum % n == 0) {
return sum/n;
} else {
return -1;
}
}
console.log(digPow(89, 1));
console.log(digPow(92, 1));
console.log(digPow(46288, 3));
My Code
This is what I did back when I answered this question. Hope this helps.
function digPow(n, p){
var digPowSum = 0;
var temp = n;
while (temp > 0) {
digPowSum += Math.pow(temp % 10, temp.toString().length + p - 1);
temp = Math.floor(temp / 10);
}
return (digPowSum % n === 0) ? digPowSum / n : -1;
}
console.log(digPow(89, 1));
console.log(digPow(92, 1));
console.log(digPow(46288, 3));
You have multiple problems:
If n is a number it is not going to have a length property. So i is going to be undefined and your loop never runs since undefined is not greater or equal to zero
for(i=n.length-1;i>=0;i--) //could be
for(i=(""+n).length;i>=0;i--) //""+n quick way of converting to string
You never initialize sum to 0 so it is undefined and when you add the result of the power calculation to sum you will continually get NaN
var sum; //should be
var sum=0;
You have if(holder<10)...break you do not need this as the loop will end after the iteration where holder is a less than 10. Also you never do a power for it or add it to the sum. Simply remove that if all together.
Your end code would look something like:
function digPow(n, p) {
var i;
var sum=0;
var myArray = new Array();
if (n < 0) {
return 0;
}
var holder;
holder = n;
for (i = (""+n).length - 1; i >= 0; i--) {
myArray[i] = holder % 10;
holder = Math.trunc(holder / 10);
myArray[i] = Math.pow(myArray[i], p + i);
sum = myArray[i] + sum;
}
if (sum % n == 0) {
return sum / n;
} else {
return -1;
}
}
Note you could slim it down to something like
function digPow(n,p){
if( isNaN(n) || (+n)<0 || n%1!=0) return -1;
var sum = (""+n).split("").reduce( (s,num,index)=>Math.pow(num,p+index)+s,0);
return sum%n ? -1 : sum/n;
}
(""+n) simply converts to string
.split("") splits the string into an array (no need to do %10 math to get each number
.reduce( function,0) call's the array's reduce function, which calls a function for each item in the array. The function is expected to return a value each time, second argument is the starting value
(s,num,index)=>Math.pow(num,p+index+1)+s Fat Arrow function for just calling Math.pow with the right arguments and then adding it to the sum s and returning it
I have created a code that does exactly what you are looking for.The problem in your code was explained in the comment so I will not focus on that.
FIDDLE
Here is the code.
function digPow(n, p) {
var m = n;
var i, sum = 0;
var j = 0;
var l = n.toString().length;
var digits = [];
while (n >= 10) {
digits.unshift(n % 10);
n = Math.floor(n / 10);
}
digits.unshift(n);
for (i = p; i < l + p; i++) {
sum += Math.pow(digits[j], i);
j++;
}
if (sum % m == 0) {
return sum / m;
} else
return -1;
}
alert(digPow(89, 1))
Just for a variety you may do the same job functionally as follows without using any string operations.
function digPow(n,p){
var d = ~~Math.log10(n)+1; // number of digits
r = Array(d).fill()
.map(function(_,i){
var t = Math.pow(10,d-i);
return Math.pow(~~((n%t)*10/t),p+i);
})
.reduce((p,c) => p+c);
return r%n ? -1 : r/n;
}
var res = digPow(46288,3);
console.log(res);

JavaScript - Improving algorithm for finding square roots of perfect squares without Math.sqrt

I'm trying to learn algorithms and coding stuff by scratch. I wrote a function that will find square roots of square numbers only, but I need to know how to improve its performance and possibly return square roots of non square numbers
function squareroot(number) {
var number;
for (var i = number; i >= 1; i--) {
if (i * i === number) {
number = i;
break;
}
}
return number;
}
alert(squareroot(64))
Will return 8
Most importantly I need to know how to improve this performance. I don't really care about its limited functionality yet
Here is a small improvement I can suggest. First - start iterating from 0. Second - exit loop when the square of root candidate exceeds the number.
function squareroot(number) {
for (var i = 0; i * i <= number; i++) {
if (i * i === number)
return i;
}
return number; // don't know if you should have this line in case nothing found
}
This algo will work in O(√number) time comparing to initial O(n) which is indeed performance improvement that you asked.
Edit #1
Just even more efficient solution would be to binary search the answer as #Spektre suggested. It is known that x2 is increasing function.
function squareroot(number) {
var lo = 0, hi = number;
while(lo <= hi) {
var mid = Math.floor((lo + hi) / 2);
if(mid * mid > number) hi = mid - 1;
else lo = mid + 1;
}
return hi;
}
This algo has O(log(number)) running time complexity.
The stuff that you try to do is called numerical methods. The most rudimentary/easy numerical method for equation solving (yes, you solve an equation x^2 = a here) is a Newtons method.
All you do is iterate this equation:
In your case f(x) = x^2 - a and therefore f'(x) = 2x.
This will allow you to find a square root of any number with any precision. It is not hard to add a step which approximate the solution to an integer and verifies whether sol^2 == a
function squareRoot(n){
var avg=(a,b)=>(a+b)/2,c=5,b;
for(let i=0;i<20;i++){
b=n/c;
c=avg(b,c);
}
return c;
}
This will return the square root by repeatedly finding the average.
var result1 = squareRoot(25) //5
var result2 = squareRoot(100) //10
var result3 = squareRoot(15) //3.872983346207417
JSFiddle: https://jsfiddle.net/L5bytmoz/12/
Here is the solution using newton's iterative method -
/**
* #param {number} x
* #return {number}
*/
// newstons method
var mySqrt = function(x) {
if(x==0 || x == 1) return x;
let ans, absX = Math.abs(x);
let tolerance = 0.00001;
while(true){
ans = (x+absX/x)/2;
if(Math.abs(x-ans) < tolerance) break;
x = ans;
}
return ans;
};
Separates Newton's method from the function to approximate. Can be used to find other roots.
function newton(f, fPrime, tolerance) {
var x, first;
return function iterate(n) {
if (!first) { x = n; first = 1; }
var fn = f(x);
var deltaX = fn(n) / fPrime(n);
if (deltaX > tolerance) {
return iterate(n - deltaX)
}
first = 0;
return n;
}
}
function f(n) {
return function(x) {
if(n < 0) throw n + ' is outside the domain of sqrt()';
return x*x - n;
};
}
function fPrime(x) {
return 2*x;
}
var sqrt = newton(f, fPrime, .00000001)
console.log(sqrt(2))
console.log(sqrt(9))
console.log(sqrt(64))
Binary search will work best.
let number = 29;
let res = 0;
console.log((square_root_binary(number)));
function square_root_binary(number){
if (number == 0 || number == 1)
return number;
let start = 0;
let end = number;
while(start <= end){
let mid = ( start + end ) / 2;
mid = Math.floor(mid);
if(mid * mid == number){
return mid;
}
if(mid * mid < number){
start = mid + 1;
res = mid;
}
else{
end = mid - 1;
}
}
return res;
}
If you analyze all natural numbers with their squares you might spot a pattern...
Numbers Squares Additives
1 1 3
2 4 5
3 9 7
4 16 9
5 25 11
6 36 13
7 49 15
Look at the first row in the squares column (i.e 1) and add it with the first row in the additives column (ie. 3). You will get four which is in the second row of the squares column.
If you keep repeating this you'll see that this applies to all squares of natural numbers. Now if you look at the additives column, all the numbers below are actually odd.
To find the square root of a perfect square you should keep on subtracting it with consecutive odd numbers (starting from one) until it is zero. The number of times it could be subtracted is the square root of that number.
This is my solution in typescript...
function findSquareRoot(number: number): number {
for (let i = 1, count = 0; true; number -= i, i += 2, count++) {
if (number <= 0) {
return number === 0 ? count : -1; // -1 if number is not a perfect square
}
}
}
Hopefully this has better time complexity :)
I see this solution on Github which is the much better and easiest approach to take a square root of a number without using any external library
function TakingPerfectSquare(Num) {
for (var i = 0; i <= Num; i++) {
var element = i;
if ((element == element) && (element*element == Num)) {
return true;
}
}
return false;
}
console.log(TakingPerfectSquare(25));

Categories

Resources