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"))
Related
function sumDigits(num) {
newStr = num.toString();
var sum = 0;
for(var i=0; i < newStr.length; i++) {
sum = sum + parseInt(newStr[i]);
}
return sum;
}
var output = sumDigits(1148);
console.log(output); // --> 14
Hey guys, my output is 14. However, my for loop falls apart if num is a negative number. Anyone got any ideas how to get past this? Presently, a negative number returns 'NaN'
I would suggest using a modulus approach here, which avoids the unnecessary cast from integer to string and vice-versa:
function sumDigits(num) {
var sum = 0;
while (num != 0) {
sum += num % 10;
num = num > 0 ? Math.floor(num / 10) : Math.ceil(num / 10);
}
return sum;
}
var output = sumDigits(1148);
console.log("1148 => " + output);
var output = sumDigits(-1148);
console.log("-1148 => " + output);
output = sumDigits(0);
console.log("0 => " + output);
Multiply the result?
function sumDigits(input) {
return Math.abs(input)
.toString()
.split("")
.reduce((sum, num) => sum + Number(num), 0)
* (input < 0 ? -1 : 1);
}
One of the examples.
function sumDigits(num) {
newStr = Math.abs(num).toString();
var sum = 0;
for(var i=0; i < newStr.length; i++) {
sum = sum + parseInt(newStr[i]);
}
return num >= 0 ? sum : -sum ;
}
var output = sumDigits(1148);
console.log(output); // --> 14
var output = sumDigits(-1148);
console.log(output); // --> -14
var output = sumDigits(0);
console.log(output); // --> 0
When you pass a negative number into your sumDigits() function and convert it to a string, the first character becomes the sign (-). So, you should get the absolute value to get rid of the sign. However, if you're expecting a negative value, then you should define a flag that indicates whether the parameter was a negative integer before it got converted, or simply multiply it again by the initial sign. So, you should modify your function like this:
function sumDigits(num) {
const seq = Math.abs(num).toString();
let sum = 0;
for (let i = 0; i < seq.length; i++) {
sum += parseInt(seq[i]);
}
return sum * Math.sign(num);
}
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)}` )
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);
How would I calculate the number of decimal places (not digits) of a real number with Javascript?
function countDecimals(number) {
}
For example, given 245.395, it should return 3.
Like this:
var val = 37.435345;
var countDecimals = function(value) {
let text = value.toString()
// verify if number 0.000005 is represented as "5e-6"
if (text.indexOf('e-') > -1) {
let [base, trail] = text.split('e-');
let deg = parseInt(trail, 10);
return deg;
}
// count decimals for number in representation like "0.123456"
if (Math.floor(value) !== value) {
return value.toString().split(".")[1].length || 0;
}
return 0;
}
countDecimals(val);
The main idea is to convert a number to string and get the index of "."
var x = 13.251256;
var text = x.toString();
var index = text.indexOf(".");
alert(text.length - index - 1);
Here is a method that does not rely on converting anything to string:
function getDecimalPlaces(x,watchdog)
{
x = Math.abs(x);
watchdog = watchdog || 20;
var i = 0;
while (x % 1 > 0 && i < watchdog)
{
i++;
x = x*10;
}
return i;
}
Note that the count will not go beyond watchdog value (defaults to 20).
I tried some of the solutions in this thread but I have decided to build on them as I encountered some limitations. The version below can handle: string, double and whole integer input, it also ignores any insignificant zeros as was required for my application. Therefore 0.010000 would be counted as 2 decimal places. This is limited to 15 decimal places.
function countDecimals(decimal)
{
var num = parseFloat(decimal); // First convert to number to check if whole
if(Number.isInteger(num) === true)
{
return 0;
}
var text = num.toString(); // Convert back to string and check for "1e-8" numbers
if(text.indexOf('e-') > -1)
{
var [base, trail] = text.split('e-');
var deg = parseInt(trail, 10);
return deg;
}
else
{
var index = text.indexOf(".");
return text.length - index - 1; // Otherwise use simple string function to count
}
}
You can use a simple function that splits on the decimal place (if there is one) and counts the digits after that. Since the decimal place can be represented by '.' or ',' (or maybe some other character), you can test for that and use the appropriate one:
function countPlaces(num) {
var sep = String(23.32).match(/\D/)[0];
var b = String(num).split(sep);
return b[1]? b[1].length : 0;
}
console.log(countPlaces(2.343)); // 3
console.log(countPlaces(2.3)); // 1
console.log(countPlaces(343.0)); // 0
console.log(countPlaces(343)); // 0
Based on Gosha_Fighten's solution, for compatibility with integers:
function countPlaces(num) {
var text = num.toString();
var index = text.indexOf(".");
return index == -1 ? 0 : (text.length - index - 1);
}
based on LePatay's solution, also take care of the Scientific notation (ex: 3.7e-7) and with es6 syntax:
function countDecimals(num) {
let text = num.toString()
if (text.indexOf('e-') > -1) {
let [base, trail] = text.split('e-')
let elen = parseInt(trail, 10)
let idx = base.indexOf(".")
return idx == -1 ? 0 + elen : (base.length - idx - 1) + elen
}
let index = text.indexOf(".")
return index == -1 ? 0 : (text.length - index - 1)
}
var value = 888;
var valueLength = value.toString().length;
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>