Javascript: Plus one challenge - javascript

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
My solution:
/**
* #param {number[]} digits
* #return {number[]}
*/
var plusOne = function(digits) {
let num = Number(digits.join('')) + 1
const myFunc = x => Number(x);
digits = Array.from(String(num), myFunc)
return digits
};
console.log(plusOne([1,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]));
Why does the above code not work given the following argument:
[1,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]
my output:
[1,NaN,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,NaN,NaN,2,1]
expected output:
[1,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8]

Since your number is larger then MAX_SAFE_INTEGER, I'd convert the array to a BigInt so you can add 1 to that (++), this way a 9 will be converted to the expected 10
After that, use the same technique to convert it back to an array:
var plusOne = function(digits) {
let bigInt = BigInt(digits.join(''));
bigInt++;
return Array.from(bigInt.toString(), Number);
};
console.log(plusOne([1,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]));
// [ 1, 2, 3, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8 ]
This can be re-written as a fancy one-liner like so:
const plusOne = (digits) => Array.from((BigInt(digits.join('')) + 1n).toString(), Number);

Here is a implementation.
var plusOne = function (digits) {
let carry = 0;
let arr = [];
for (let i = digits.length - 1; i >= 0; i--) {
let n = Number(digits[i]);
if (i === digits.length - 1) {
n = n + 1;
} else if (carry === 1) {
n = n + 1;
}
if (n === 10) {
carry = 1;
n = 0;
}
arr.push(n)
}
return arr.reverse();
};

Looks like someone else already gave basically the same answer as I typed this, but here's my answer anyway.
It looks like you're getting this error, because the Number(digits.join('')) + 1 returns 1.2356777777777777e+21. Running Array.from(String(1.2356777777777777e+21)) by itself returns [1,.,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,e,+,2,1]. Notice you have 3 NaN values at positions 1, 18, and 19. In other words, you can't convert ".", "+", or "+" to numbers with Number(). It just returns NaN, as they are Not a Number...
Long story short—unless I misunderstand the point in the original question—you're going about it all wrong. Because your number is so big, you should use the BigInt() object. Note: It can only operate with other BigInts. Here's a working example:
const plusOne = digits => {
const num = BigInt(digits.join('')) + BigInt(1)
return num.toString().split('')
}
console.log(plusOne([1,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]))
I hope that helps.

Related

How would you make a function that adds random numbers from a list to reach a certain value?

the question title might be a little bit confusing so let me see if I can explain it a little better here. I want to create a function that will generate a sequence of numbers (in any order or combination) that are in a pre-defined list to add to a certain value.
IE.
var x = [6, 4, 3]; //pre-defined values
var n = 24; //the number I want to add too
function myFunc(values, goal) {
//code for algorithm
//return a sequence of numbers from the list that add to 24
}
myFunc(x, n)
Example Outputs from myFunc:
4, 4, 4, 6, 3, 3 --> 24
6, 4, 3, 3, 4, 4 --> 24
3, 4, 4, 6, 3, 4 --> 24
etc.
The algorithm would be able to return one of the many permutations that exist but I just came up with a couple for the sake of the question.
Responses don't have to be language-specific I just need a general idea/insight on how to create and structure this algorithm.
Thanks!
Here's a brute-force approach that keeps adding random values until the sum is 24 (return) or it's greater than 24 (restart). This may not be practical for large values.
var x = [6, 4, 3]; //pre-defined values
var n = 24; //the number I want to add too
function myFunc(values, goal) {
let result = [];
while (true) {
// Add random value
result.push(values[Math.floor(Math.random() * values.length)]);
// Calc sum
var sum = result.reduce((acc, val) => acc + val);
// If success, return
if (sum == goal) return result;
// If too large, start over
else if (sum > goal) result = [];
}
}
for (let i = 0; i < 10; i++) {
console.log(myFunc(x, n));
}

Returning the first two odd numbers in an array

I have to run a code that picks out the odd numbers in an array, and returns the first two odd numbers in that array. I've figured out how to return all of the odd numbers from the array, just not the first two.
code so far:
function oddCouple(_numberList) {
let numberList = [5, 2, 3, 1];
let oddNumbers = numberList.filter((number) => number % 2 !== 0);
console.log(oddNumbers);
}
oddCouple();
Any help would be appreciated!
Array.slice returns the selected number of items from the array starting from a specified index.
function oddCouple(_numberList) {
let oddNumbers = _numberList.filter((number) => number % 2 !== 0).slice(0, 2);
console.log(oddNumbers);
}
oddCouple([1, 2, 3, 4, 5, 6, 7, 8, 9]);
The built in method would be Array.slice. This code would be suitable for a small arrays.
For larger arrays it would be more efficient to manually loop through the source array so you are only evaluating the modulus operation for the first N odd numbers.
Additionally, division is expensive. You can check if a number is odd using the binary & operator; e.g.: (number & 1) == 1
function oddCouple(_numberList) {
let numberList = [5, 2, 3, 1];
let oddNumbers = numberList.filter((number) => (number & 1) == 1).slice(0,2);
console.log(oddNumbers);
}
oddCouple();
You can use for..of loop, and break when the array contains 2 items like so:
function oddCouple(_numberList) {
let numberList = [5, 2, 3, 1];
let arr = [];
for(let number of numberList) {
(number % 2) !== 0 && arr.push(number);
if(arr.length === 2) break;
}
console.log(arr);
}
oddCouple();
function oddCouple(_numberList) {
let numberList = [5, 2, 3, 1];
let oddNumbers = numberList.filter((number) => number % 2 !== 0).slice(0,2);
console.log(oddNumbers);
}

Generate an array of unique N random numbers which if all numbers summed up equal to N

Assume that N = 3, I want to make a function to generate 3 unique random numbers which if all numbers summed up will equal to 3. For example:
numbers = [1, 0, 2]
numbers = [2, -4, 5]
I already have my own solution in JavaScript below:
let i = 0;
let arr = []
function getRandomInt(number) {
return Math.floor(Math.random()*(number*2)) - number;
}
function generateArray(i, arr, number) {
let lastIndex = number-1;
while (i < lastIndex) {
let randomNumber = getRandomInt(number);
if (arr.indexOf(randomNumber) > -1) {
continue;
} else {
arr[i] = randomNumber;
}
i++;
}
let summed = arr.reduce((a, b) => a+b);
let lastNumber = number - summed;
if (arr.indexOf(lastNumber) > -1) {
return generateArray(lastIndex-1, arr, number);
} else {
arr[lastIndex] = lastNumber;
return arr;
}
}
But I still have a problem with the last index that tends to deviate quite a lot. For example with N = 10, I could have a result like this one below:
numbers = [2, -1, 3, 4, -4, 0, -5, -8, -6, 15]
I wonder if you guys have a much better solution with also a better performance. Thank you!
Here's a snippet that first fills an array with N unique numbers in a range between -N and N.
Then replaces the last value in the array so that the total = N.
When that recalculated final value is already part of in the array, then the function recurses.
To avoid that the last value isn't unique.
And it also recurses when that final value deviates to much.
function getArrayRandomNumbersInRange(min, max, N) {
let arr = [];
while(arr.length < N){
let num = Math.floor(Math.random() * (max - min + 1)) + min;
if(arr.indexOf(num) > -1) continue;
arr[arr.length] = num;
}
let total = arr.reduce(function(accum, val) {return accum + val});
let lastElem = arr[arr.length-1] - total + N;
if(lastElem < min || lastElem > max || (total !== N && arr.indexOf(lastElem) > -1)) {
//console.log(lastElem + ' -> recurse');
arr = [];
return getArrayRandomNumbersInRange(min, max, N);
}
arr[arr.length-1] = lastElem;
return arr;
}
function getArrayRandomNumbers(N){
return getArrayRandomNumbersInRange(-N, N, N);
}
function sumArray(arr){
return arr.reduce(function(accum, val) {return accum + val})
}
let randomUniqueArray = getArrayRandomNumbers(5);
console.log("Total:\t" + sumArray(randomUniqueArray));
console.log(randomUniqueArray);
EDITED: (I thought about this some more, and think I found an even better way, described below)
Here's what I came up with. This makes the list appear more random, and while there may be a few elements that deviate more than others, but the elements that do could be from any index. It only requires one small change.
You have:
let randomNumber = getRandomInt(number);
Replace this with:
let randomNumber = getRandomInt(number) + i - currentSum;
where currentSum is just a rolling sum of the array, and i is an incrementing variable that starts at zero and increments one every pass through, both of which you would update in the else block of the while loop. (In other words, this would replace the summed variable you have as this would keep track of the sum as the array is generating random numbers). What this change aims to do is to normalize the random number to not have the sum go to far from the what the rolling some is supposed to be around. To sum n numbers to add to n, the 'trivial' solution would be to have every number be 1 (i.e. the rolling sum is just the index of the array). What the above code change does is create a random number that generates random numbers around the expected rolling sum I just described. Thus, if I were to run the code a million times, the average value of every value in the array would be 1, which is perfect with regards to wanting a list as you described. I tested this method in Java real quick and it seems to do what you want, so I hope this 'quick fix' helps.
Another idea (I did not test this one though) to further reduce deviation would be to, in addition to the above change, make the generateRandomInt() function generate numbers in a smaller bound, as right now this function generates numbers with a range of 2 * number, which could produce bigger numbers than you want.
Here are a few test arrays I got when I ran my the changed code (with number = 10):
[-3, 10, 0, -4, -1, 6, -5, 5, -7, 9]
[-6, -2, 4, 6, -8, 8, 3, -4, 7, 2]
[-2, 4, -10, 1, 6, 13, -3, -6, 12, -5]
I hope you get the idea of this; hope this helps!
P.S. I believe the code you posted should have the i++ command inside the else block, as otherwise you might not fill up the entire array.

How to write the code with less time complexity for finding the missing element in given array range?

My function should return the missing element in a given array range.
So i first sorted the array and checked if the difference between i and i+1 is not equal to 1, i'm returning the missing element.
// Given an array A such that:
// A[0] = 2
// A[1] = 3
// A[2] = 1
// A[3] = 5
// the function should return 4, as it is the missing element.
function solution(A) {
A.sort((a,b) => {
return b<a;
})
var len = A.length;
var missing;
for( var i = 0; i< len; i++){
if( A[i+1] - A[i] >1){
missing = A[i]+1;
}
}
return missing;
}
I did like above, but how to write it more efficiently??
You could use a single loop approach by using a set for missing values.
In the loop, delete each number from the missing set.
If a new minimum value is found, all numbers who are missing are added to the set of missing numbers, except the minimum, as well as for a new maximum numbers.
The missing numbers set contains at the end the result.
function getMissing(array) {
var min = array[0],
max = array[0],
missing = new Set;
array.forEach(v => {
if (missing.delete(v)) return; // if value found for delete return
if (v < min) while (v < --min) missing.add(min); // add missing min values
if (v > max) while (v > ++max) missing.add(max); // add missing max values
});
return missing.values().next().value; // take the first missing value
}
console.log(getMissing([2, 3, 1, 5]));
console.log(getMissing([2, 3, 1, 5, 4, 6, 7, 9, 10]));
console.log(getMissing([3, 4, 5, 6, 8]));
Well, from the question (as it's supposed to return a single number) and all the existing solution (examples at least), it looks like list is unique. For that case I think we can sumthe entire array and then subtracting with the expected sum between those numbers will generate the output.
sum of the N natural numbers
1 + 2 + ....... + i + ... + n we can evaluate by n * (n+1) / 2
now assume, in our array min is i and max is n
so to evaluate i + (i+1) + ..... + n we can
A = 1 + 2 + ..... + (i-1) + i + (i+1) + .... n (i.e. n*(n+1)/2)
B = 1 + 2 + ..... + (i-1)
and
C = A - B will give us the sum of (i + (i+1) + ... + n)
Now, we can iterate the array once and evaluate the actual sum (assume D), and C - D will give us the missing number.
Let's create the same with each step at first (not optimal for performance, but more readable) then we will try to do in a single iteration
let input1 = [2, 3, 1, 5],
input2 = [2, 3, 1, 5, 4, 6, 7, 9, 10],
input3 = [3, 4, 5, 6, 8];
let sumNatural = n => n * (n + 1) / 2;
function findMissing(array) {
let min = Math.min(...array),
max = Math.max(...array),
sum = array.reduce((a,b) => a+b),
expectedSum = sumNatural(max) - sumNatural(min - 1);
return expectedSum - sum;
}
console.log('Missing in Input1: ', findMissing(input1));
console.log('Missing in Input2: ', findMissing(input2));
console.log('Missing in Input3: ', findMissing(input3));
Now, lets try doing all in a single iteration (as we were iterating 3 times for max, min and sum)
let input1 = [2, 3, 1, 5],
input2 = [2, 3, 1, 5, 4, 6, 7, 9, 10],
input3 = [3, 4, 5, 6, 8];
let sumNatural = n => n * (n + 1) / 2;
function findMissing(array) {
let min = array[0],
max = min,
sum = min,
expectedSum;
// assuming the array length will be minimum 2
// in order to have a missing number
for(let idx = 1;idx < array.length; idx++) {
let each = array[idx];
min = Math.min(each, min); // or each < min ? each : min;
max = Math.max(each, max); // or each > max ? each : max;
sum+=each;
}
expectedSum = sumNatural(max) - sumNatural(min - 1);
return expectedSum - sum;
}
console.log('Missing in Input1: ', findMissing(input1));
console.log('Missing in Input2: ', findMissing(input2));
console.log('Missing in Input3: ', findMissing(input3));
Instead of sorting, you could put each value into a Set, find the minimum, and then iterate starting from the minimum, checking if the set has the number in question, O(N). (Sets have guaranteed O(1) lookup time)
const input1 = [2, 3, 1, 5];
const input2 = [2, 3, 1, 5, 4, 6, 7, 9, 10];
const input3 = [3, 4, 5, 6, 8];
function findMissing(arr) {
const min = Math.min(...arr);
const set = new Set(arr);
return Array.from(
{ length: set.size },
(_, i) => i + min
).find(numToFind => !set.has(numToFind));
}
console.log(findMissing(input1));
console.log(findMissing(input2));
console.log(findMissing(input3));
If the array is items and the difference between missing and present diff is 1:
const missingItem = items => [Math.min(...items)].map(min => items.filter(x =>
items.indexOf(x-diff) === -1 && x !== min)[0]-diff)[0]
would give complexity of O(n^2).
It translates to: find the minimum value and check if there isn't a n-diff value member for every value n in the array, which is also not the minimum value. It should be true for any missing items of size diff.
To find more than 1 missing element:
([Math.min(...items)].map(min => items.filter(x =>
items.indexOf(x-diff) === -1 && x !== min))[0]).map(x => x-diff)
would give O((m^2)(n^2)) where m is the number of missing members.
Found this old question and wanted to take a stab at it. I had a similar thought to https://stackoverflow.com/users/2398764/koushik-chatterjee in that I think you can optimize this by knowing that there's always only going to be one missing element. Using similar methodology but not using a max will result in this:
function getMissing(arr) {
var sum = arr.reduce((a, b) => a + b, 0);
var lowest = Math.min(...arr);
var realSum = (arr.length) * (arr.length + 1) / 2 + lowest * arr.length;
return realSum - sum + lowest;
}
With the same inputs as above. I ran it in jsperf on a few browsers and it is faster then the other answers.
https://jsperf.com/do-calculation-instead-of-adding-or-removing.
First sum everything, then calculate the lowest and calculate what the sum would be for integers if that happened to be the lowest. So for instance if we have 2,3,4,5 and want to sum them that's the same as summing 0,1,2,3 and then adding the lowest number + the amount of numbers in this case 2 * 4 since (0+2),(1+2),(2+2),(3+2) turns it back into the original. After that we can calculate the difference but then have to increase it once again by the lowest. To offset the shift we did.
You can use while loop as well, like below -
function getMissing(array) {
var tempMin = Math.min(...array);
var tempMax = tempMin + array.length;
var missingNumber = 0;
while(tempMin <= tempMax){
if(array.indexOf(tempMin) === -1) {
missingNumber = tempMin;
}
tempMin++;
}
return missingNumber;
}
console.log(getMissing([2, 3, 1, 5]));
console.log(getMissing([2, 3, 1, 5, 4, 6, 7, 9, 10]));
console.log(getMissing([3, 4, 5, 6, 8]));
My approach is based on in place sorting of the array which is O(N) and without using any other data structure.
Find the min element in the array.
Sort in place.
Again loop the array and check if any element is misplaced, that is the answer!
function getMissing(ar) {
var mn = Math.min(...ar);
var size = ar.length;
for(let i=0;i<size;i++){
let cur = ar[i];
// this ensures each element is in its right place
while(cur != mn +i && (cur - mn < size) && cur != ar[cur- mn]) {
// swap
var tmp = cur;
ar[i] = ar[cur-mn];
ar[cur-mn] = tmp;
}
}
for(let i=0; i<size; i++) {
if(ar[i] != i+mn) return i+mn;
}
}
console.log(getMissing([2, 3, 1, 5]));
console.log(getMissing([2, 3, 1, 5, 4, 6, 7, 9, 10]));
console.log(getMissing([3, 4, 5, 6, 8]));

JavaScript Number Split into individual digits

I am trying to solve a math problem where I take a number e.g. 45, or 111 and then split the number into separate digits e.g. 4 5 or 1 1 1. I will then save each number to a var to run a method on. Does anyone know how to split a number into individual digitals?
For example I have a loop that runs on an array :
for (var i = 0; i < range.length; i++) {
var n = range[i];
}
For each number, I would like to split its digits and add them together?
var num = 123456;
var digits = num.toString().split('');
var realDigits = digits.map(Number)
console.log(realDigits);
var number = 12354987,
output = [],
sNumber = number.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}
console.log(output);
/* Outputs:
*
* [1, 2, 3, 5, 4, 9, 8, 7]
*/
UPDATE: Calculating a sum
for (var i = 0, sum = 0; i < output.length; sum += output[i++]);
console.log(sum);
/*
* Outputs: 39
*/
You can also do it in the "mathematical" way without treating the number as a string:
var num = 278;
var digits = [];
while (num != 0) {
digits.push(num % 10);
num = Math.trunc(num / 10);
}
digits.reverse();
console.log(digits);
One upside I can see is that you won't have to run parseInt() on every digit, you're dealing with the actual digits as numeric values.
This is the shortest I've found, though it does return the digits as strings:
let num = 12345;
[...num+''] //["1", "2", "3", "4", "5"]
Or use this to get back integers:
[...num+''].map(n=>+n) //[1, 2, 3, 4, 5]
I will provide a variation on an answer already given so you can see a different approach that preserves the numeric type all along:
var number = 12354987,
output = [];
while (number) {
output.push(number % 10);
number = Math.floor(number/10);
}
console.log(output.reverse().join(',')); // 1,2,3,5,4,9,8,7
I've used a technique such as the above to good effect when converting a number to Roman numerals, which is one of my favorite ways to begin to learn a programming language I'm not familiar with. For instance here is how I devised a way to convert numbers to Roman numerals with Tcl slightly after the turn of the century: http://code.activestate.com/recipes/68379-conversion-to-roman-numerals/
The comparable lines in my Tcl script being:
while {$arabic} {
set digit [expr {$arabic%10}]
set arabic [expr {$arabic/10}]
// Split positive integer n < 1e21 into digits:
function digits(n) {
return Array.from(String(n), Number);
}
// Example:
console.log(digits(1234)); // [1, 2, 3, 4]
You can work on strings instead of numbers to achieve this. You can do it like this
(111 + '').split('')
This will return an array of strings ['1','1','1'] on which you can iterate upon and call parseInt method.
parseInt('1') === 1
If you want the sum of individual digits, you can use the reduce function (implemented from Javascript 1.8) like this
(111 + '').split('').reduce(function(previousValue, currentValue){
return parseInt(previousValue,10) + parseInt(currentValue,10);
})
Use String, split and map :
String(number).split("").map(Number);
function splitNum(num) {
return String(num).split("").map(Number);
}
console.log(splitNum(1523)); // [1, 5, 2, 3]
console.log(splitNum(2341)); // [2, 3, 4, 1]
console.log(splitNum(325)); // [3, 2, 5]
Without converting to string:
function toDigits(number) {
var left;
var results = [];
while (true) {
left = number % 10;
results.unshift(left);
number = (number - left) / 10;
if (number === 0) {
break;
}
}
return results;
}
Using String, ... and map
const num = 7890;
const digits = [...String(num)].map(Number);
console.log(digits)
Alternatively, using ... and reduce to get digits and their sum.
const sumOfDigits = num => [...""+num].reduce((acc, dig) => acc + +dig, 0);
console.log('Sum of digits: ', sumOfDigits(7890));
Separate each 2 parametr.
function separator(str,sep) {
var output = '';
for (var i = str.length; i > 0; i-=2) {
var ii = i-1;
if(output) {
output = str.charAt(ii-1)+str.charAt(ii)+sep+output;
} else {
output = str.charAt(ii-1)+str.charAt(ii);
}
}
return output;
}
console.log(separator('123456',':')); //Will return 12:34:56
With ES6, you could use Array.from with a stringed number as iterables and Number as mapping function.
const getDigits = n => Array.from(n.toString(), Number);
console.log(getDigits(12345));
A fun introduction to recursion. This answer takes a Number and returns an array of Number digits. It does not convert the number to a string as an intermediate step.
Given n = 1234,
n % 10 will return first (right-moist) digit, 4
n / 10 will return 123 with some remainder
Using Math.floor we can chop the remainder off
Repeating these steps, we can form the entire result
Now we just have to build the recursion condition,
If the number is already a single digit (n < 10), return an array singleton of the digit
otherwise (inductive) the number is 10 or greater; recur and prepend to the first digit
const digits = (n = 0) =>
n < 10
? [ n ]
: [ ... digits (Math.floor (n / 10)), n % 10 ]
console.log (digits ()) // [ 0 ]
console.log (digits (1)) // [ 1 ]
console.log (digits (12)) // [ 1, 2 ]
console.log (digits (123)) // [ 1, 2, 3 ]
console.log (digits (11234)) // [ 1, 2, 3, 4 ]
console.log (digits (123456789012))
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 ]
This also works:
var number = 12354987;
console.log(String(number).split('').map(Number));
Shadow Wizard , extended version by Orien
var num:Number = 1523;
var digits:Array = [];
var cnt:int = 0;
while (num > 0) {
var mod:int = num % 10;
digits.push(mod * Math.pow(10, cnt))
num = Math.floor(num / 10);
cnt++;
}
digits.reverse();
trace(digits);
output:1000,500,20,3
A functional approach in order to get digits from a number would be to get a string from your number, split it into an array (of characters) and map each element back into a number.
For example:
var number = 123456;
var array = number.toString()
.split('')
.map(function(item, index) {
return parseInt(item);
});
console.log(array); // returns [1, 2, 3, 4, 5, 6]
If you also need to sum all digits, you can append the reduce() method to the previous code:
var num = 123456;
var array = num.toString()
.split('')
.map(function(item, index) {
return parseInt(item);
})
.reduce(function(previousValue, currentValue, index, array) {
return previousValue + currentValue;
}, 0);
console.log(array); // returns 21
As an alternative, with ECMAScript 2015 (6th Edition), you can use arrow functions:
var number = 123456;
var array = number.toString().split('').map((item, index) => parseInt(item));
console.log(array); // returns [1, 2, 3, 4, 5, 6]
If you need to sum all digits, you can append the reduce() method to the previous code:
var num = 123456;
var result = num.toString()
.split('')
.map((item, index) => parseInt(item))
.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
console.log(result); // returns 21
I used this simple way of doing it.
To split digits
var N = 69;
var arr = N.toString().split('').map(Number)
// outputs [6,9]
console.log( arr );
To add them together
console.log(arr.reduce( (a,b) => a+b )); // 15
And the easiest.... num_string.split('').map(Number)
Try below:
console.log((''+123).split('').map(Number))
To just split an integer into its individual digits in the same order, Regular Expression is what I used and prefer since it prevents the chance of loosing the identity of the numbers even after they have been converted into string.
The following line of code convert the integer into a string, uses regex to match any individual digit inside the string and return an array of those, after which that array is mapped to be converted back to numbers.
const digitize = n => String(n).match(/\d/g).map(Number);
I might be wrong, but a solution picking up bits and pieces. Perhaps, as I still learning, is that the functions does many things in the same one. Do not hesitate to correct me, please.
const totalSum = (num) => [...num + ' '].map(Number).reduce((a, b) => a + b);
So we take the parameter and convert it to and arr, adding empty spaces. We do such operation in every single element and push it into a new array with the map method. Once splited, we use reduce to sum all the elements and get the total.
As I said, don't hesitate to correct me or improve the function if you see something that I don't.
Almost forgot, just in case:
const totalSum = (num) => ( num === 0 || num < 0) ? 'I need a positive number' : [...num + ' '].map(Number).reduce((a, b) => a + b);
If negatives numbers or just plain zero go down as parameters. Happy coding to us all.
I am posting this answer to introduce the use of unshift which is a modern solution. With push, you add to the end of an array while unshift adds to the beginning. This makes the mathematical approach more powerful as you won't need to reverse anymore.
let num = 278;
let digits = [];
while (num > 0) {
digits.unshift(num % 10);
num = parseInt(num / 10);
}
console.log(digits);
var num = 111,
separateDigits = num.toString().split(""), i, l = separateDigits.length;
for( i = 0; i < l; ++i ) {
someObject.someMethod( +separateDigits[i] );
}
You can try this.
var num = 99;
num=num.toString().split("").map(value=>parseInt(value,10)); //output [9,9]
Hope this helped!
function iterateNumber(N, f) {
let n = N;
var length = Math.log(n) * Math.LOG10E + 1 | 0;
for (let i = 0; i < length; i++) {
const pow = Math.pow(10, length - i - 1)
let c = (n - (n % pow)) / pow
f(c, i)
n %= pow
}
}
('' + 123456789).split('').map( x => +x ).reduce( (a,b) => a+b ) === 45
true
or without map
('' + 123456789).split('').reduce( (a,b) => (+a)+(+b) ) === 45
true
You can do it in single line, seperate each digits than add them together :
var may = 12987;
var sep = (""+may).split("").map(n=>+n).reduce((a,b)=>a+b);
This is my short solution.. with sum of number
function sum (num) {
let sNumber = num
.toString()
.split('')
.reduce((el1, el2) => {
return Number(el1) + Number(el2)
}, 0)
return sNumber
}
console.log(sum(123))
console.log(sum(456))
javascript has a function for it and you can use it easily.
console.log(new Intl.NumberFormat().format(number));
for example :
console.log(new Intl.NumberFormat().format(2334325443534));
==> 2,334,325,443,534
Iterate through each number with for...of statement.
By adding a + sign before a String, it will be converted into a number.
const num = 143,
digits = [];
for (const digit of `${num}`) {
digits.push(+digit)
}
console.log(digits);
Inspired by #iampopov You can write it with spread syntax.
const num = 143;
const digits = [...`${num}`].map(Number);
console.log(digits);
And as a one liner.
console.log(Number.MAX_SAFE_INTEGER.toString().split('').reduce((pv, v) => Number(v) + pv, 0));

Categories

Resources