Palindrome says infinity when compared in the final if statement - javascript

ok so I have been going at it for a while im making a palindrome program on html for the first time but when I input 111 it says its not a palindrome even tho i went through the while loop with a calc and it should be the same. I checked the outputs by revealing em and
"input" = 111.
"temp" = 0 as it should.
"reversed" tho is equal to infinity lol and idk y any help is appreciated.
function Palindrome() {
let input = document.querySelector("#userInput").value;
var temp = input;
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = (reversed * 10) + lastDigit;
temp = (temp / 10);
}
if (input == reversed) {
document.querySelector("#answer").innerHTML = `This is a Palindrome `;
}else {
document.querySelector("#answer").innerHTML = `This is not a Palindrome ${input} ${temp} ${reversed} `;
}
}

You're doing floating point division, so temp will never be more than 0 until you do many iterations and get floating point underflow. After each iteration it becomes 11.1, then 1.11, then 0.111, .0111, and so on. This is multiplying reversed by 10 each time, and it eventually overflows to infinity.
Round the number when dividing so that the fraction will be discarded:
temp = Math.round(temp / 10);
function Palindrome(input) {
var temp = input;
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = (reversed * 10) + lastDigit;
temp = Math.round(temp / 10);
}
if (input == reversed) {
console.log(`This is a Palindrome ${input}`);
} else {
console.log(`This is not a Palindrome ${input} ${temp} ${reversed} `);
}
}
Palindrome(111);
Palindrome(123)

As Barmar explained in his answer about percent division try to git rid of it!
function Palindrome() {
let input = document.querySelector("#userInput").value;
//convert input to number
var temp = +input;//or parseInt(input)
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = reversed * 10 + lastDigit;
temp = Math.floor(temp / 10);//<-- to prevent Infinity
}
if (input == reversed) {
document.querySelector("#answer").innerHTML = `This is a Palindrome `;
} else {
document.querySelector(
"#answer"
).innerHTML = `This is not a Palindrome ${input} ${temp} ${reversed} `;
}
}
<input type="input" value="" id="userInput">
<input type="button" value="Is Palindrom" onclick="Palindrome()">
<div id='answer'></div>

Related

How to swap first and last digits of a number using for loop in Javascript

I need to ask user to input a 3 digit number and then swap the first and last numbers using a for loop. This is what I have so far, but I'm stuck. Using a for loop seems illogical, but that is what I have to do:
num = prompt("Please input a number with 3 digits.");
let firstDigit = num[0];
let secondDigit = num[1];
let lastDigit = num[2];
for (firstDigit < 10; secondDigit < 10; lastDigit < 10); {
console.log(lastDigit + secondDigit + firstDigit);
}
Please help!
Thanks
is it help for you?
// let num = prompt("Please input a number with 3 digits.");
// if (num.length > 3) alert("3 digits please");
// else {
// let answer = "";
// for (var i = 2; i >= 0; i--) {
// answer = answer + num[i];
// }
// console.log(answer);
//}
let num = prompt("Please input a number");
let temp = "";
let answer = "";
for(let i = 0 ; i < num.length; i++) {
if (i === 0) temp = num[i]; // save first number to temp
else if (i === num.length - 1) {
// When the last number is encountered, the last number is put at the beginning, and the first number stored in temp is put at the end.
answer = answer + temp;
answer = num[i] + answer;
}
else answer = answer + num[i];
}
console.log(answer);

Adding Strings With Float Numbers Javascript

I'm trying to solve a question to be able to add strings that include floating point numbers. For example "110.75" + "9" = "119.75".
I have the code below that I have been wrestling with for about an hour now and could appreciate if anybody could point me in the right direction as to where I might be wrong. I am only returning an empty string "" for every test case I write for myself.
var addStrings = function(num1, num2) {
const zero = 0;
let s1 = num1.split(".");
let s2 = num2.split(".");
result = "";
let sd1 = s1.length > 1 ? s1[1] : zero;
let sd2 = s2.length > 1 ? s2[1] : zero;
while(sd1.length !== sd2.length) {
if(sd1.length < sd2.length) {
sd1 += zero
} else {
sd2 += zero;
}
}
let carry = addStringHelper(sd1, sd2, result, 0);
result.concat(".");
addStringHelper(s1[0], s2[0], result, carry);
return result.split("").reverse().join("");
};
function addStringHelper(str1, str2, result, carry) {
let i = str1.length - 1;
let j = str2.length - 1;
while(i >= 0 || j >= 0) {
let sum = carry
if(j >= 0) {
sum += str1.charAt(j--) - '0';
}
if(i >= 0 ) {
sum += str2.charAt(i--) - '0';
}
carry = sum / 10;
result.concat(sum % 10);
}
return carry
}
Convert the strings into Number, add them and then convert them back to String.
const addStrings = (num1, num2) => String(Number(num1) + Number(num2))
console.log(addStrings("110.67", "9"))
Also, try to handle floating point rounding in some way. You can try using toFixed (this will fix the result to two decimal places).
const addStrings = (num1, num2) => String((Number(num1) + Number(num2)).toFixed(2))
console.log(addStrings("0.2", "0.1"))

How to calculate the factorial of a number entered by user in Javascript, using, do-loop, while-loop?

Quick follow-up question on my previous question. I'd like to add the code to the following to calculate the factorial of a number entered by user in Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers !=null){
alert("Finally you entered a correct number");
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum+=counter;
counter++;
}
while (counter<=numOfLoops)
alert ("The sum of numbers from 1 to " + numbers + "is =" +sum);
}
</script>
</head>
<body>
<script>
document.write("<h1>Sum of Numbers</h1>");
document.write("The sum of numbers from 1 to = " + numbers + " is = " +
+ sum + "<br><br>");
</script>
</body>
</html>
If you are trying to sum up the numbers, consider using arithmetic series formula. If you're trying to get the factorial, the approach is shown below.
If you want to sum using the loop, just change the *= to +=.
While Loop Approach
const fact = (n) => {
let res = 1;
while (n > 0) {
res *= n;
n--;
}
return res;
}
fact(5) // 120
Do While Approach
const fact = (n) => {
let res = 1;
do {
res *= n;
n--;
} while (n > 0)
return res;
}
fact(3) // 6
That should do the trick. :)
Maybe also considering checking for edge cases like if the n is negative.
Good luck.
While Loop:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
while(n) r *= n--
return r
}
Do While:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
do r *= n || 1 // in case of n == 0
while (n--)
return r;
}
complete code
const
msgPrompt_1 = 'Please enter a number from 0 to 100',
msgPrompt_n = 'Try again.... Enter a number 0-100',
fact = n =>
{
let r = 1
while(n) r *= n--
return r
}
let numValue = parseInt(window.prompt(msgPrompt_1, ''), 10)
while(isNaN(numValue) || numValue > 100 || numValue < 0)
{
numValue = parseInt(window.prompt(msgPrompt_n, ''), 10)
}
alert(`factorial value of ${numValue} is = ${fact(numValue)}` )

Finding multiples of 7 between 2 given integers

I'm trying to return a string (a comma-separated list) of all numbers between two given integers that are multiples of 7. I know how to find the multiples with the modulus operator but not between 2 given numbers. I'm new to JS and learning. Help is greatly appreciated.
Starting with something like this:
function findMultiplesOfSeven(startNumber, endNumber) {
return string;
}
You could take the start value and add the remainder value for getting the first wanted value.
i = startValue + startValue % 7 // 5 + 2 => 7
Then iterate and loop until the value is greater then the end value.
for (i = startValue + startValue % 7; i <= endValue; i += 7) {
// add value
}
Here is my sample code:
function findMultiplesOfSeven(startNumber, endNumber) {
let multiples = [];
let walk = startNumber + (7 - startNumber % 7);
while(walk <= endNumber) {
multiples.push(walk);
walk += 7;
}
let string = multiples.join(',')
return string;
}
function findMultiplesOfSeven(startNumber, endNumber) {
let containsNumberDivisibleBy7 = false;
let firstNumber;
let numbers = [];
for (var i = startNumber; i <= endNumber; i++) {
if (i % 7 === 0) {
containsNumberDivisibleBy7 = true;
firstNumber = i;
break;
}
}
if (containsNumberDivisibleBy7) {
for (var i = firstNumber; i <= endNumber; i += 7) {
numbers.push(i);
}
}
return numbers.join(",");
}

Reverse decimal digits in javascript

How do I reverse the digits of a number using bitwise?
input:
x = 123;
output:
x = 321;
How Do this?
That's not inverting bits; that's reversing the order of decimal digits, which is completely different. Here's one way:
var x = 123;
var y = 0;
for(; x; x = Math.floor(x / 10)) {
y *= 10;
y += x % 10;
}
x = y;
If you actually want to invert bits, it's:
x = ~x;
As a function:
function reverse(n) {
for(var r = 0; n; n = Math.floor(n / 10)) {
r *= 10;
r += n % 10;
}
return r;
}
If you wanted to make a simple reversal:
var x = 123;
var y = x.toString();
var z = y.split("").reverse().join("");
var aa = Number(z);
document.write(aa);
http://jsfiddle.net/jasongennaro/gV39e/
Here is another way...
var reversed = num.toString().split('').reverse().join('');
jsFiddle.
If you wanted it again as a Number, use parseInt(reversed, 10). Keep in mind though, leading 0s are not significant in a decimal number, and you will lose them if you convert to Number.
you also use this function
function myfunction(a){
var x=a.toString();
var y= x.split("");
var z=y.reverse();
var result=z.join("");
return result;
}
myfunction(123);
Simple and quick solution: Let's assume that you want to reverse a number 4546. You will take the reminder from each division by 10 and append it to the result until the number is > 0. And simultaneously updating the num variable by dividing it by 10.
var x = '';
var num = 4546;
while(num>0){
x = x + (num%10);
num = parseInt(num/10);
}
console.log(x);
Reversing The Positive/ Negative Integer Number
function reverseInt(n) {
return parseInt(n.toString().split('').reverse().join()) * Math.sign(n)
}
If n is -5, then Math.sign(n)==> will return -1
If n is 5, then Math.sign(n)==> will return 1
Here are reversible array functions in JavaScript that handle integers or strings:
function reverse(array)
{
var left = null;
var right = null;
var length = array.length;
for (left = 0, right = length - 1; left < right; left += 1, right -= 1)
{
var temporary = array[left];
array[left] = array[right];
array[right] = temporary;
}
return array;
}
function toDigitsArrayFromInteger(integer, isReverse)
{
var digits = [];
if (integer > 0)
{
var floor = window.Math.floor;
while (integer > 0)
{
digits.push(floor(integer % 10));
integer = floor(integer / 10);
}
// Array is populated in reverse order. Un-reverse it to make it normal.
if (!isReverse)
{
digits = reverse(digits);
}
}
else if (integer < 0)
{
digits = toDigitsArrayFromInteger(-integer, isReverse);
}
else if (integer === 0)
{
digits.push(0);
}
return digits;
}
function toDigitsArrayFromString(string, isReverse)
{
var digits = [];
string += ""; // Coerce to string.
var i = null;
var length = string.length;
for (i = 0; i < length; i += 1)
{
var integer = parseInt(string.charAt(i), 10);
if (isFinite(integer))
{
digits.push(integer);
}
}
if (isReverse)
{
digits = reverse(digits);
}
return digits;
}
Once you have the digits as an array, you can reverse the array easily to get the digits starting from the left or from the right.
The string function is more versatile because it can find any digit in a string, whereas the integer function is limited to integers.
Benchmarks:
http://jsperf.com/todigitsarray
The benchmarks between the two functions show that in Firefox 10 and Chrome 12, the string function is 30% to 60% faster than the integer function. In Opera 12, the integer function is slightly faster by about 10%.
//reverse integer
const revInt = (num)=>{
//turn into string
if(Math.sign(num)===1)
return parseInt(num.toString().split('').reverse().join(''));
else return -1*parseInt(num.toString().split('').reverse().join(''));
}
console.log(revInt(-501));
<html>
<script>
function reverseInt(n){
var r=0;
while(n!=0){
r*=10;
r+=n%10;
n=Math.floor(n/10);
}
return r;
}
</script>
</html>
try this
var n = 352;
function loop(n, r){
if(!n) return r;
r = (r ? r * 10 : 0) + n % 10;
return loop(Math.floor( n / 10), r);
}
console.log(loop(n));
OK, how about using and chaining these popular tricks in JavaScript in one-line function as below...
const reverseNum = num => +("" + ~~num.split("").reverse().join(""));
And call it like these:
reverseNum(123); //321
reverseNum(423.09); //324
reverseNum(23305.1); //50332
reverseNum(89112); //21198
reverseNum(568434.2389); //434865
This takes Number x as a parameter and returns the reversed number.
const reverse = (x) => Number(x.toString().split("").reverse().join(""));
Memory Usage: 35.3 MB, less than 100.00% of JavaScript online submissions for Reverse Integer on leetcode.com.
Runtime: 80 ms, faster than 61.48% of JavaScript online submissions for Reverse Integer.
Time complexity is O(log10(n)).
function reverse(x) {
let rev = 0;
const isNegative = Math.sign(x) === -1;
const isOverflow = n => n > 2**31;
x = Math.abs(x);
while (x) {
let pop = x % 10;
x = Math.floor(x / 10);
rev = rev * 10 + pop;
if (isOverflow(rev)) {
return 0;
}
}
return isNegative ? rev * -1 : rev;
}
The code block below should do the trick
<script type = "text/javascript">
var input;
input=window.prompt ("Please enter a number to be reversed.");
x=input.length;
while(x > 0)
{
x=x-1;
document.write(input[x]);
}
</script>

Categories

Resources