/**
* #param {number} x
* #return {boolean}
*/
var isPalindrome = function(x) {
var y=x,num=0,rem;
while(x>0)
{
rem=x%10;
num=(num*10)+rem;
x=x/10;
}
if(num==y)
return true;
else
return false ;
};
I am still getting wrong output as false but my logic is correct.
This is leetcode palindrome question i am trying it with javascript logic is correct but still not able to figure it out.
There is just one issue:
In JavaScript numbers are floating point numbers by default, and so / performs a floating point division. You need to truncate that:
x = Math.floor(x / 10);
A remark on your code:
The construct if (boolean) return true; else false is an anti-pattern. Since boolean already represents the value you want to return, you should just return it. So in your case do:
return num == y;
Your logic seems fine but execution is having some minor errors. Please use below snippet, it should work:
var isPalindrome = function(x) {
if (x < 0) {
return false;
}
// Store the number in a variable
let number = x;
// This will store the reverse of the number
let reverse = 0;
while (number > 0) {
reverse = reverse * 10 + number % 10;
number = parseInt(number / 10);
}
return x === reverse;
}
Related
I want to check if a value is in an accepted range. If yes, to do something; otherwise, something else.
The range is 0.001-0.009. I know how to use multiple if to check this, but I want to know if there is any way to check it in a single if statement.
You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple if" statements to do it, either:
if (x >= 0.001 && x <= 0.009) {
// something
}
You could write yourself a "between()" function:
function between(x, min, max) {
return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
// something
}
Here is an option with only a single comparison.
// return true if in range, otherwise false
function inRange(x, min, max) {
return ((x-min)*(x-max) <= 0);
}
console.log(inRange(5, 1, 10)); // true
console.log(inRange(-5, 1, 10)); // false
console.log(inRange(20, 1, 10)); // false
If you must use a regexp (and really, you shouldn't!) this will work:
/^0\.00([1-8]\d*|90*)$/
should work, i.e.
^ nothing before,
followed by 0.00 (nb: backslash escape for the . character)
followed by 1 through 8, and any number of additional digits
or 9, followed by any number of zeroes
$: followed by nothing else
If you're already using lodash, you could use the inRange() function:
https://lodash.com/docs/4.17.15#inRange
_.inRange(3, 2, 4);
// => true
_.inRange(4, 8);
// => true
_.inRange(4, 2);
// => false
_.inRange(2, 2);
// => false
_.inRange(1.2, 2);
// => true
_.inRange(5.2, 4);
// => false
_.inRange(-3, -2, -6);
// => true
I like Pointy's between function so I wrote a similar one that worked well for my scenario.
/**
* Checks if an integer is within ±x another integer.
* #param {int} op - The integer in question
* #param {int} target - The integer to compare to
* #param {int} range - the range ±
*/
function nearInt(op, target, range) {
return op < target + range && op > target - range;
}
so if you wanted to see if x was within ±10 of y:
var x = 100;
var y = 115;
nearInt(x,y,10) = false
I'm using it for detecting a long-press on mobile:
//make sure they haven't moved too much during long press.
if (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);
If you want your code to pick a specific range of digits, be sure to use the && operator instead of the ||.
if (x >= 4 && x <= 9) {
// do something
} else {
// do something else
}
// be sure not to do this
if (x >= 4 || x <= 9) {
// do something
} else {
// do something else
}
You must want to determine the lower and upper bound before writing the condition
function between(value,first,last) {
let lower = Math.min(first,last) , upper = Math.max(first,last);
return value >= lower && value <= upper ;
}
const inRange = (num, num1, num2) => Math.min(num1, num2) <= num && Math.max(num1, num2) >= num;
Could be like this if you want to make inRange inclusive and not depend on order of range numbers (num1, num2).
I've been learning javascript in school for a few months now and I'm trying to work a problem out on my own but I can't seem to figure out what the issue is. The assignment is to "Create a for loop that starts at zero and loops once for each character in the number using the .length property." So for example, if I were to put in 2514 it should return 12.
Here is the piece I'm struggling with
function sumOfDigits(numberPassed) {
if (!isNaturalNumber(numberPassed)) {
return 'bad data';
} else {
numberPassed = parseInt(numberPassed)
let digitSum = 0;
for (let i = 0; i < numberPassed.length; i++) {
digitSum = numberPassed[i] + digitSum;
}
return digitSum;
}
}
When I test it in the browser it keeps giving me 0. If anyone could point me in the right direction I would greatly appreciate it.
function sumOfDigits(numberPassed) {
if (!isNaturalNumber(numberPassed)) {
return 'bad data';
} else {
numberPassed = parseInt(numberPassed)
let digitSum = 0;
for (let i = 0; i < numberPassed.toString().length; i++) {
digitSum = numberPassed[i] + digitSum;
}
return digitSum;
}
}
It seems that your implementation is incredibly close to the solution that I found.
What the problem is, is that the value of parseInt(numberPassed) is no longer a string, which means its length cannot be read. So you have to one of many solutions. For example:
Make numberPassed a string in the for loop by doing for (let i = 0; i < numberPassed.toString().length; i++)
Don't parse the numberPassed until it is ready to be used as a number. Or create a secondary variable that is the same just set to a string.
There are many other solutions to this problems, but for the most part it is moving around the parseInt() or the .toString() around with the numberPassed, so to make it easier in the future you can use variables similar to intNumberPassed = parseInt(numberPassed) and stringNumberPassed = numberPassed.toString() if you need to switch between the two often
If you would like more of an explanation or more solutions to the problem here they are.
So when you have a string you can measure the length easily, but when you convert it to a number, instead of a list of binary numbers like a word would be, it is a singular value, aka 12 would be 1100 but when you convert it to a string '12' is would be equivalent to 00110001 00110010 which are the unicode to binary values for '12', giving us a length of two, instead of a length of one.
Do not parse your number string into an int, if you want to loop over each digit like it was an array.
function isNaturalNumber(numberStr) {
return /^\d+$/.test(numberStr);
}
function sumOfDigits(numberPassed) {
if (!isNaturalNumber(numberPassed)) {
return 'bad data';
}
let digitSum = 0;
for (let i = 0; i < numberPassed.length; i++) {
digitSum += parseInt(numberPassed[i], 10);
}
return digitSum;
}
console.log(sumOfDigits('2514')); // 12
If you want to parse it first, you will have to use some logarithmic math to extract each digit. String manipulation is less expensive in JavaScript, so this one is much-less performant.
function numDigits(n) {
return Math.max(Math.floor(Math.log10(Math.abs(n))), 0) + 1;
}
function getDigit(n, offset, fromLeft) {
const magnitude = fromLeft ? numDigits(n) - offset : offset + 1;
return Math.floor((n / Math.pow(10, magnitude - 1)) % 10);
}
function isNaturalNumber(numberStr) {
return /^\d+$/.test(numberStr);
}
function sumOfDigits(numberPassed) {
if (!isNaturalNumber(numberPassed)) {
return 'bad data';
}
const natural = parseInt(numberPassed, 10);
const digits = numDigits(natural);
let digitSum = 0;
for (let i = 0; i < digits; i++) {
digitSum += getDigit(natural, i);
}
return digitSum;
}
console.log(sumOfDigits('2514')); // 12
Credit for getDigit calculation: https://stackoverflow.com/a/41712226/1762224
If you want the most ES6 way to achieve this, give this a shot:
/**
* Determines if a given string is a natural number.
* #param {string} numStr - A number string
* #returns {boolean} The given string represents a natural number
*/
const isNaturalNumber = numStr => /^\d+$/.test(numStr)
/**
* Sums the digits of a given number or number string.
* #param {(number|string)} num - A number or number string
* #returns {number} The sum of all the digits
*/
const sumOfDigits = num =>
(numStr =>
isNaturalNumber(numStr)
? numStr.split('').reduce((sum, d) => sum + parseInt(d, 10), 0)
: 'bad data')
(num ? num.toString() : '')
console.log(sumOfDigits(2514)) // 12
console.log(sumOfDigits('2514')) // 12
console.log(sumOfDigits(5e2)) // 5
console.log(sumOfDigits('5e2')) // 'bad data'
parseInt() would convert numberPassed into a number. Thus, you wont be able to perform .length method to it.
You'd have to convert it into a string through, numberPassed.toString() and then while you are performing your addition, convert each digit back to INT through parseInt(numberPassed[i]) to get your desired result.
The code would look something like this,
function sumOfDigits(numberPassed) {
if (!isNaturalNumber(numberPassed)) {
return 'bad data';
} else {
numberPassed = numberPassed.toString()
let digitSum = 0;
for (let i = 0; i < numberPassed.length; i++) {
digitSum = parseInt(numberPassed[i]) + digitSum;
}
return digitSum;
}
}
I am trying to solve a leetcode [problem][1]. The question says to search in a 2d array. While my code passes for most of the test cases it fails for a particular test case.
/**
* #param {number[][]} matrix
* #param {number} target
* #return {boolean}
*/
/**
* #param {number[][]} matrix
* #param {number} target
* #return {boolean}
*/
var searchMatrix = function(matrix, target) {
let i = 0 ;
let j = matrix.length ;
while(i <= matrix.length - 1 && j >= 0){
if(matrix[i][j] == target){
return true
}
if(matrix[i][j] > target){
j--;
} else {
i++;
}
}
return false
};
searchMatrix([1,3],3)
Above solution gives false whereas the correct answer should be true. What's wrong here ? Cant find out !
[1]: https://leetcode.com/problems/search-a-2d-matrix/
This question has two variations one on Leetcode and another on Geeks for Geeks.
Your solution above would work for GFG platform but would fail on leetcode.
Why?
Variation in both question lies how elements are arranged. In leetcode question first element of every row will be greater than last element of the previous row, which is not in the case of GFG. On GFG you will have row and column wise sorted matrix.
Your solution would pass the GFG test cases but would fail on leetcode. Hence one of the optimized solutions that you can go with is to use its question property and imagine it as a one dimensional array.
function searchMatrix(matrix, target){
let numberOfRows = matrix.length
let numberOFColums = matrix[0].length
let upperBoundOfMatrix = numberOfRows * numberOFColums - 1;
let start = 0
while(start <= upperBoundOfMatrix){
let mid = Math.floor(start + (upperBoundOfMatrix - start)/2);
let row = Math.floor(mid/numberOFColums);
let column = Math.floor(mid % numberOFColums);
if(matrix[row][column] == target){
return true
}
if(matrix[row][column] > target){
upperBoundOfMatrix = mid - 1;
} else {
start = mid + 1;
}
}
return false
}
I am creating a function that returns whether the passed in number is odd Without the modulo operator. The tricky part is that it should work for NEGATIVE numbers and ZERO.
here's my codes so far:
function testodd(num) {
return (num/2)*2==num;
}
var output = testodd(17);
console.log(output); // --> true
Am I making some mistakes here? Or is there a better way to do this?
you can use Bitwise operator and get same result. does this help.
<script type="text/javascript">
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
console.log(oddOrEven(10));
</script>
For more detail about bitwise operator
Hi you can do it with bitwise AND (&) operator to check if a number is even or odd.
function testodd(num) {
if((num & 1) == 0){
return true
}
return false;
}
var output = testodd(17);
console.log(output); // --> false
var output = testodd(-16);
console.log(output); // --> true
var output = testodd(0);
console.log(output); // --> true
Try a bit-wise operation
function testodd(num) {
return num & 1; // num AND 0x1 checks for the least significant bit, indicating true or falsey
}
Remove the decimal part after division using Math.floor.
Math.floor(num / 2) * 2 === num;
For even numbers, there is no loss in decimal value. For odd numbers, decimal point value will be lost and comparison will falsy.
Here is a horribly inefficient method using recursion:
function checkOdd(num)
{
num = Math.abs(num);
if(num==0)
return false;
else if(num==1)
return true;
else
return checkOdd(num-2);
}
Of course you should never use it.
Since there's already an answer I will show you an alternative away of doing it with regex
function checkOdd(num){
console.log(/^\d*[13579]$/.test(num));
}
checkOdd(105);
Would only work with reasonably sized integers
Try
function testodd(num){
if num < 0{
var number = -num
}
int i = 1;
int product = 0;
while (product <= num)
{
product = divisor * i;
i++;
}
// return remainder
return num - (product - divisor);
}
Use this function to check if a number is odd or even, without using the modulo operator %. This should work for negative numbers and zero.
function checkOdd(num) {
// your code here
if(num<0){ //Check if number is negative
num=-num; //Convert it into positive number
}
let b=Math.floor(num/2) //Taking value for loop iteration
for(var i=1;i<=b;i++){
num=num-2; //Will check the number is odd if it subtraction end to 1 by decrementing -2 to the number
if(num==1){
return true; //return true if number is odd
}
}
return false; //return false if number is even
}
You can use isInteger method
function isEven(n){
return Number.isInteger(n / 2);
}
function odd(num) {
if (num === 0) {
return false;
}
num = Math.abs(num);
while (num >= 2) {
num = num - 2;
}
if (num === 1) {
return true;
} else {
return false;
}
}
Even number
lets take an even number say 6;
6 divided by 2 is 3;
Math.round(3) is 3;
Math.floor(3) is 3;
3===3 eveluates to true so 6 is an even number;
Odd number
lets take an odd number say 9;
9 divided by 2 is 4.5;
Math.round(4.5) is 5;
Math.floor(4.5) is 4;
5===4 evaluates to false so 9 is an odd number;
function evenChecked(num) {
if (Math.round(num / 2) === Math.floor(num / 2)) {
return `${num} is even`;
} else {
return `${num} is odd`;
}
}
console.log(evenChecked(23));
console.log(evenChecked(90));
console.log(evenChecked(56));
console.log(evenChecked(49));
I'm trying to understand how recursion works in javascript. But I'm having problems even getting this function to work properly.
example problem shows calculating power and "potentially" setting the results of the calculation to innerHTML of var my header:
var myHeader= document.getElementById("myHeader");
var answer = 0;
answer = power(10, 5);
function power(base, exponent) {
if(exponent == 0)
return 0;
else
return base * power(base, exponent - 1);
}
myHeader.innerHTML = answer;
Could you please edit this example code to make it work?
Example code
I just want to use chrome debuggers so I can set a breakpoint and walk through the function one by one to see the order of operations.
I'm taking this function from eloquent javascript by Marijin Haverbeke
Your power function is wrong
function power(n, p) {
if(p == 0)
{
return 1; // see Math.pow(5, 0) for example
}
return power(n, p - 1) * n;
}
and
document.getElementById('myHeader').innerHTML = power(5, 10);
You have 2 problems :
1 You used var answer = 0, you didn't assign it to get the result from power.
2 Inside your function, you returned 0 if exponent === 0, so basically, when exponent = 0, you are returning base * power(base, 0) which equals to base * 0 which in turn equals to 0, so your function will always return 0.
var myHeader= document.getElementById("myHeader");
var answer = power(10,5);
function power(base, exponent) {
if(exponent === 0)
return 1;
else
return base * power(base, exponent - 1);
}
myHeader.innerHTML = answer;
myHeader.innerHTML = power(10,5);
If you are looking for some ref parameters like in C#: function(param1, param2, ref param3), no, JavaScript has no such parameter.
If you're just looking to get the power function working, then this is a better solution:
document.getElementById("myHeader").innerHTML = Math.pow(10,5);