This question already has answers here:
Sum all the digits of a number Javascript
(8 answers)
Closed 6 years ago.
given var num = 123456 how can I find the sum of its digits (which is 21 in this case) without using arrays?
var num = 123456, sum = 0;
while ( num > 0 ) { sum += (num % 10)|0; num /= 10; }
document.write(sum);
Hope this helps.!
console.log(sumofdigits(123456));
function sumofdigits(number) {
var sum = 0;
while (number > 0) {
sum += number % 10;
number = Math.floor(number / 10);
}
return sum;
}
Added console.log() as suggested by #nnnnnn
Related
This question already has answers here:
Sum all the digits of a number Javascript
(8 answers)
Closed 5 months ago.
Let's suppose I have an integer value as
const num = 123456789
and I want to print the sum of these no. in react as 1+2+3+4+5+6+7+8+9 = 45
expect output = 45
approach I am following is as follows
const [total, setTotal] = useState(0);
const num = 123456789
for (const element of num ) {
setTotal(total + element)
}
console.log(total)
Output I am getting is : 01
Need your help here please!
You can continuously divide by 10 until the number becomes 0 and use % 10 to get the last digit.
let num = 123456789;
let sum = 0;
for (; num; num = Math.floor(num / 10))
sum += num % 10;
console.log(sum);
A one-liner
const num = 123456789
console.log(num.toString().split('').reduce((acc, elem) => elem*1+acc, 0))
This question already has answers here:
Number with leading zeroes gets changed in JavaScript
(4 answers)
Why JavaScript treats a number as octal if it has a leading zero
(3 answers)
Closed 1 year ago.
solving Sum of Digits / Digital Root and facing problem in this case where input is 010 the output comes 8.
please can anyone explain?
function fun(n) {
let numString = n.toString().split("");
let sum = 0;
for (let i = 0; i < numString.length; i++) {
sum += parseInt(numString[i]);
}
console.log(sum);
if (sum >= 10) {
return fun(sum);
}
console.log(numString);
return sum;
}
console.log(fun(010)); // input- 010 and output- 8
Why the output is 8 but it should be 1.
This question already has answers here:
Javascript number comparison fails
(2 answers)
Closed 4 years ago.
Challenge:
You are given a string of space-separated numbers and have to return the highest and lowest number.
Problem:
Expected: '542 -214', instead got: '6 -214'
I can't understand why the system thinks 6 is higher than 542. The program works fine when the 6 is removed.
Code:
function highAndLow(numbers){
numbers = numbers.split(" ");
var biggest = numbers[0];
for (i = 0; i < numbers.length; i++) {
if (numbers[i] > biggest) {
biggest = numbers[i];
}
}
var smallest = numbers[0];
for (i = 0; i < numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
return biggest + " " + smallest;
}
console.log(highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"));
JSBin Link
This is because it's comparing the numbers as strings instead of as numbers. You'll want to convert them to numbers using the Number() function to convert them to numbers before you compare them, for example:
biggest = Number(numbers[0]);
I was given a quiz and I had gotten the answer wrong and It's been bugging me ever since so I thought I'd ask for your thoughts
I needed to optimise the following function
function sumOfEvenNumbers(n) {
var sum = 0;
for(let i = 2; i < n;i++){
if(i % 2 == 0) sum += i;
}
return sum;
}
console.log(sumOfEvenNumbers(5));
I came up with
function sumOfEvenNumbers(n) {
var sum = 0;
while(--n >= 2) sum += n % 2 == 0? n : 0
return sum;
}
console.log(sumOfEvenNumbers(5));
What other ways were there?
It's a bit of a math question. The sum appears to be the sum of an arithmitic sequence with a common difference of 2. The sum is:
sum = N * (last + first) / 2;
where N is the number of the numbers in the sequence, last is the last number of those numbers, and first is the first.
Translated to javascript as:
function sumOfEvenNumbers(n) {
return Math.floor(n / 2) * (n - n % 2 + 2) / 2;
}
Because the number of even numbers between 2 and n is Math.floor(n / 2) and the last even number is n - n % 2 (7 would be 7 - 7 % 2 === 6 and 8 would be 8 - 8 % 2 === 8). and the first is 2.
Sum of n numbers:
var sum = (n * (n+1)) / 2;
Sum of n even numbers:
var m = Math.floor(n/2);
var sum = 2 * (m * (m+1) /2);
You can compute these sums using an arithmetic sum formula in constant time:
// Return sum of positive even numbers < n:
function sumOfEvenNumbers(n) {
n = (n - 1) >> 1;
return n * (n + 1);
}
// Example:
console.log(sumOfEvenNumbers(5));
Above computation avoids modulo and division operators which consume more CPU cycles than multiplication, addition and bit-shifting. Pay attention to the limited range of the bit-shifting operator >> though.
See e.g. http://oeis.org/A002378 for this and other formulas leading to the same result.
First thing is to eliminate the test in the loop:
function sumOfEvenNumbers(n) {
var sum = 0;
var halfN= Math.floor(n/2);
for(let i = 1; i < n/2;i++) {
sum += i;
}
return sum * 2;
}
Then we can observe that is just calculating the sum of all the integers less than a limit - and there is a formula for that (but actually formula is for less-equal a limit).
function sumOfEvenNumbers(n) {
var halfNm1= Math.floor(n/2)-1;
var sum = halfNm1 * (halfNm1+1) / 2;
return sum * 2;
}
And then eliminate the division and multiplication and the unnecessary addition and subtraction:
function sumOfEvenNumbers(n) {
var halfN= Math.floor(n/2);
return (halfN-1) * halfN;
}
Your solution computes in linear (O(N)) time.
If you use a mathematical solution, you can compute it in O(1) time:
function sum(n) {
let half = Math.ceil(n/2)
return half * (half + 1)
}
Because the question is tagged ecmascript-6 :)
const sumEven = x => [...Array(x + 1).keys()].reduce((a, b) => b % 2 === 0 ? a + b : a, 0);
// set max number
console.log(sumEven(10));
This question already has answers here:
How to round an integer up or down to the nearest 10 using Javascript
(4 answers)
Closed 6 years ago.
How can I round an integer number in Javascript to the nearest 10? My math is pretty rubbish today :)
Some sample cases:
45 = 50
41 = 50
40 = 40
I understand I probably need a combination of Math.round/floor but I can't seem to get expected result.
Any help/pointers appreciated,
thanks
//Update: faster way
var getDozen = function (n) {
var r = n % 10;
// if its greater than 4
if (r > 4)
return n - r + 10;
//if its lower than 5, then subtract the remainder
else
return n - r;
}
console.log(getDozen(45)); // 50
var getDozen = function (n) {
var r = n % 10;
if (r > 4) return Math.ceil(n / 10) * 10;
else return Math.floor(n / 10) * 10;
}
console.log(getDozen(45)); // 50