Adding two integers of a double digit integer in Javascript - javascript

I was attempting a coding practice where I had to take a two digit integer, split the integer into its two digits and add those digits.
function addTwoDigits(n) {
var n = n
var string = n.toString()
var split = string.split("")
var integer= split.map(Number)
var z = integer[0]+integer[1]
console.log(z)
}
The output of my code was correct on each of the tests, but the code checks still failed. If anyone can provide some insight into why, I would appreciate it.

You could write the function this way
function addTwoDigits(n) {
return Math.floor(n/10) + (n%10));
}

I have encountered a similar issue before. The solution for me was returning the value, rather than logging it to the console.
Instead of console.log(z) try return z

Not sure what you mean by "but the code checks still failed". Here's a oneliner for n-digit numbers, using a reducer:
const sumOfIndividualDigits = n =>
[...`${n}`]
// ^ convert to Array of strings
.map(Number)
// ^convert element (back) to Numbers
.reduce( (acc, value) => acc + value, 0);
// ^ reduce to 1 value (sum)
console.log(sumOfIndividualDigits(22));
console.log(sumOfIndividualDigits(12345678));

Related

Recursive function to find binary not returning elements in single array. (Not pushing to the same )

Problem statement: I'm trying to get string > binary without using the inbuilt method in javascript.
This is a piece of program where a string input (like "ABC") is accepted, then it is translated to an array of equivalent code value ([65,66,67]).
Function binary() will change a number to binary. But I'm unable to join them together to loop through all the contents. Please help. (I'm a noob, please forgive my bad code and bad explanation)
var temp3 = [65,66,67];
var temp2 = [];
var r;
for(i=0;i<temp3.length;i++) {
var r = temp3[i];
temp2.push(binary(r));
}
function binary(r) {
if (r === 0) return;
temp2.unshift(r % 2);
binary(Math.floor(r / 2));
return temp2;
}
console.log(temp2);
I think this is a cleaner version of this function. It should work for any non-negative integers, and would be easy enough to extend to the negatives. If we have a single binary digit (0 or 1) and hence are less than 2, we just return the number converted to a string. Otherwise we call recursively on the floor of half the number (as yours does) and append the final digit.
const binary = (n) =>
n < 2
? String (n)
: binary (Math.floor (n / 2)) + (n % 2)
console.log (binary(22)) //=> '10110'
console.log ([65, 66, 67] .map (binary)) //=> ['1000001', '1000010', '1000011']
In your function you have this code
var r = temp3[i];
I don't see any temp3 variable anywhere in your code above so I'd imagine that could be causing some issues.

Sort a list by the second number after a dot

I need to sort a list by the second batch number with JavaScript.
This is how it looks like now:
1101.19
1201.17
1301.09
What I need is:
1301.09
1201.17
1101.19
As I am still learning to program I can't figure out the issue. But need it at work.
Can someone help me understand the process of how to do it?
Sort the array depending on the decimal part. Here is the solution
Sort the array by selecting the decimal part of the number inside the sort function.
You can get the decimal part of any number by taking modulus operation with 0.1. Link.
const arr = [1101.19, 1201.17, 1301.09, 1201.20];
arr.sort((a, b) => {return (a % 1 - b % 1)});
console.log(arr);
You need to split each element before sort and compare second parts
let array = ["1101.69", "1701.57", "1301.09"];
array.sort((a,b)=>{
let pair1 = a.split('.');
let pair2 = b.split('.');
return ( parseInt(pair1[1]) < parseInt(pair2[1])) ? -1 : 1;
});
console.log(array);

continually add values in javascript with while loop

I'm a newbie to Javascript so please bear with me for this basic question,
I'm trying to get my function to add all the individual digits in a string together, and then keep doing this until I'm left with a single digit!
3253611569939992595156
113 // result of the above digits all added together
5 //result of 1+1+3
I've created a while loop, but it only adds the numbers together once, it dosn't repeat until a single digit and I can't work out why!
function rootFunc(n) {
var splite = n.toString().split('').map(x => Number(x)); //converts the number to a string, splits it and then converts the values back to a number
while (splite.length > 1) {
splite = splite.reduce(getSum);
}
return splite;
}
console.log(rootFunc(325361156993999259515));
function getSum(total, num) {
return total + num;
}
You're reducing properly, but what you're not doing is re-splitting. Try breaking this out into separate functions:
function digits(n) {
return n.toString().split('').map(x =>Number(x));
}
Then split each time:
function rootFunc(n) {
var d = digits(n);
while (d.length > 1) {
d = digits(d.reduce(getSum));
}
return d;
}
The problem here is that you return the result after the first splice. You need to have a recursive function. To do this, you can put this before the return :
if(splite > 9) splite = rootFunc(splite);
This way, you check if the result is greater than 10, if not you do the function with the remaining digits
I was looking this over in jsfiddle, and your number isn't being passed to exact precision, so just console logging n as soon as you call rootFunc, you've already lost data. Otherwise, to fix your loop, you need to remap splite to a string before the end of your codeblock since your while statement is checking .length, which needs to be called on a string. Put this piece of code at the end of the block:
splite = splite.toString().split('').map(x =>Number(x));

Why is the last element of my array being replaced with a 0

I have a function:
function splitToDigits(n) {
var digits = ("" + n).split("").map(function(item) {
return parseInt(item, 10);
});
console.log(digits);
}
console.log(splitToDigits(123456784987654321));
This is returning digits = [1,2,3,4,5,6,7,8,4,9,8,7,6,5,4,3,2,0].
Any idea why the last element is 0? I noticed that when I delete 2 elements from the array it acts normally. Thanks for all the great answers! :)
As Jaromanda X mentioned in the comments section above, JavaScript does not have enough precision to keep track of every digit in the integer you passed to your function.
To fix this problem, you should instead pass a string:
console.log(splitToDigits('123456784987654321'))
However, I would also like to point out that you can greatly simplify your splitToDigits method:
function splitToDigits(n) {
return [].map.call(n + '', Number)
}
console.log(splitToDigits('123456784987654321'))
console.log(splitToDigits(1234))
It's because Javascript is truncating numbers.
The best way to see this is by doing this console.log:
function splitToDigits(n) {
console.log(n);
var digits = ("" + n).split("").map(function(item) {
return parseInt(item, 10);
});
}
Then, when you ran: splitToDigits(123456784987654321), you already get 123456784987654320. Hence, it has nothing to do with your code as you have still not processed it.
If you add digits, it changes to scientific notation:
splitToDigits(1234567849876543211521521251) // turns to 1.2345678498765432e+27
It's a Javascript precision issue. That's all :)

using the digits of a number as an array

var number = 342345820139586830203845861938475676
var output = []
var sum = 0;
while (number) {
output.push(number % 10);
number = Math.floor(number/10);
}
output = output.reverse();
function addTerms () {
for (i = 0; i < output.length; i=i+2) {
var term = Math.pow(output[i], output[i+1]);
sum += term;
}
return sum;
}
document.write(output);
document.write("<br>");
document.write(addTerms());
I am trying to take that large number and split it into its digits. Then, find the sum of the the first digit raised to the power of the 2nd, 3rd digit raiseed to the 4th, 5th raised to the 6th and so on. for some reason, my array is returning weird digits, causing my sum to be off. the correct answer is 2517052. Thanks
You're running into precision issues within JavaScript. Just evaluate the current value of number before you start doing anything, and the results may surprise you:
>>> var number = 342345820139586830203845861938475676; number;
3.423458201395868e+35
See also: What is JavaScript's highest integer value that a Number can go to without losing precision?
To resolve your issue, I'd store your input number as an array (or maybe even a string), then pull the digits off of that.
This will solve your calculation with the expected result of 2517052:
var number = "342345820139586830203845861938475676";
var sum = 0;
for(var i=0; i<number.length; i=i+2){
sum += Math.pow(number.charAt(i), number.charAt(i+1));
}
sum;
JavaScript stores numbers in floating point format (commonly double). double can store precisely only 15 digits.
You can use string to store this large number.
As mentioned, this is a problem with numeric precision. It applies to all programming languages that use native numeric formats. Your problem works fine if you use a string instead
var number = '342345820139586830203845861938475676'
var digits = number.split('')
var total = 0
while (digits.length > 1) {
var [n, power] = digits.splice(0, 2)
total += Math.pow(n, power)
}
(the result is 2517052, byt the way!)
Cast the number as a string and then iterate through it doing your math.
var number = "342345820139586830203845861938475676";//number definition
var X = 0;//some iterator
var numberAtX = 0 + number.charAt(X);//number access
The greatest integer supported by Javascript is 9007199254740992. So that only your output is weird.
For Reference go through the link http://ecma262-5.com/ELS5_HTML.htm#Section_8.5
[edit] adjusted the answer based on Borodins comment.
Mmm, I think the result should be 2517052. I'd say this does the same:
var numbers = '342345820139586830203845861938475676'.split('')
,num = numbers.splice(0,2)
,result = Math.pow(num[0],num[1]);
while ( (num = numbers.splice(0,2)) && num.length ){
result += Math.pow(num[0],num[1]);
}
console.log(result); //=> 2517052
The array methods map and reduce are supported in modern browsers,
and could be worth defining in older browsers. This is a good opportunity,
if you haven't used them before.
If you are going to make an array of a string anyway,
match pairs of digits instead of splitting to single digits.
This example takes numbers or strings.
function sumPower(s){
return String(s).match(/\d{2}/g).map(function(itm){
return Math.pow(itm.charAt(0), itm.charAt(1));
}).reduce(function(a, b){
return a+b;
});
}
sumPower('342345820139586830203845861938475676');
alert(sumPower(s))
/*
returned value:(Number)
2517052
*/

Categories