Sum of all digits of a number - javascript

Given Problem:
Write a function called "sumDigits".
Given a number, "sumDigits" returns the sum of all its digits.
var output = sumDigits(1148);
console.log(output); // --> 14
If the number is negative, the first digit should count as negative.
var output = sumDigits(-316);
console.log(output); // --> 4
My code:
function sumDigits(num) {
return num.toString().split("").reduce(function(a, b){
return parseInt(a) + parseInt(b);
});
}
My code solves the problem for positive integers. Any hints on how should I go about solving the problem for negative integers? Please and thanks.
Edit: And what if the given number is 0? Is it acceptable to add an if statement to return 0 in such cases?

Check to see if the first character is a -. If so, b is your first numeral and should be negative:
function sumDigits(num) {
return num.toString().split("").reduce(function(a, b){
if (a == '-') {
return -parseInt(b);
} else {
return parseInt(a) + parseInt(b);
}
});
}

You could use String#match instead of String#split for a new array.
function sumDigits(num) {
return num.toString().match(/-?\d/g).reduce(function(a, b) {
return +a + +b;
});
}
console.log(sumDigits(1148)); // 14
console.log(sumDigits(-316)); // 4

Somebody who is looking for a solution without reduce functions etc. can take this approach.
function sumDigits(num) {
var val = 0, remainder = 0;
var offset = false;
if (num <0) {
offset = true;
num = num * -1;
}
while (num) {
remainder = num % 10;
val += remainder;
num = (num - remainder) / 10;
}
if (offset) {
val -= 2 * remainder;//If the number was negative, subtract last
//left digit twice
}
return val;
}
var output = sumDigits(-348);
console.log(output);
output = sumDigits(348);
console.log(output);
output = sumDigits(1);
console.log(output);

//Maybe this help: // consider if num is negative:
function sumDigits(num){
let negativeNum = false;
if(num < 0){
num = Math.abs(num);
negativeNum = true;
}
let sum = 0;
let stringNum = num.toString()
for (let i = 0; i < stringNum.length; i++){
sum += Number(stringNum[i]);
}
if(negativeNum){
return sum - (Number(stringNum[0]) * 2);
// stringNum[0] has the "-" sign so deduct twice since we added once
} else {
return sum;
}
}

Related

Error in true false output in Array Problem

Here's the question:
A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
For example, take 153 (3 digits), which is narcisstic:
1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10.
My Code is:
function narcissistic(value) {
let vLen = value.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Math.pow(value[i], vLen);
}
if (sum == value) {
return true;
} else {
return false;
}
}
But I'm getting errors. What should I do?
Numbers don't have .length, convert to string first
vLen[i], you cant treat a number as array, again, convert to string to use that syntax.
The return can be simplefied to return (sum === value);
function narcissistic(value) {
let sVal = value.toString();
let vLen = sVal.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Math.pow(sVal[i], vLen);
}
return (sum === value);
}
console.log(narcissistic(153));
console.log(narcissistic(111));
Well... There are several things wrong with this code, but I think there is mostly a problem with the types of your input.
I'll show you how you can cast the types of your input to make sure you work with the types you need:
Also... You should try to avoid using the == operator and try to use === instead (same goes for != and !==), because the == and != don't try to match the types, resulting in sometimes unpredictable results
function narcissistic(value) {
valueStr = String(value);
let vLen = valueStr.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Number(valueStr[i]) ** vLen;
}
if (sum === value) {
return true;
} else {
return false;
}
}
if(narcissistic(153)) {
console.log("narcissistic(153) is true!") // expected value: true
}
All the first 9 digits from 1 to 9 is Narcissistic number as there length is 1 and there addition is always same.
So, first we are checking weather the number is greater than 9 or not.
if(num>9) =>false than it's a narcissistic number.
-if(num>9) =>true than we have to split number into digits for that I have used x = num.toString().split('');. Which is first converting number to String and than using split() function to split it.
Than , we are looping through each digit and digitsSum += Math.pow(Number(digit), x.length); adding the power of digit to const isNarcissistic = (num) => { let x = 0; let digitsSum.
at the end, we are comparing both num & digitsSum if there are matched than number is narcissistic else not.
const isNarcissistic = (num) => {
let x = 0;
let digitsSum = 0;
if (num > 9) {
x = num.toString().split('');
x.forEach(digit => {
digitsSum += Math.pow(Number(digit), x.length);
});
if (digitsSum == num) {
return true;
} else {
return false;
}
} else {
return true;
}
}
console.log(isNarcissistic(153));
console.log(isNarcissistic(1634));
console.log(isNarcissistic(1433));
console.log(isNarcissistic(342));

Recursive function to reverse a number

I tried to use a recursive function to reverse a number it works but for one call only it's because of scoping i guess but i don't know how to fix it
let num;
let reversed='';
let result;
function reverseNum(n){
for(let i =0; i<n; i++){
num = n%10; // get the last digit e.g 352 %10 = 2
reversed+= num
result = parseInt(n / 10); // remove last digit e.g. parseInt(352/10) = 35
reverseNum(result);
if(result ===0){
break;
}
}
return reversed;
}
You need the num, reversed, and result variables to be created anew each time the function is called externally. Here's one simple tweak, by defining the recursive function inside the top reverseNum function:
function reverseNum(n) {
let num;
let reversed = '';
let result;
const recurse = (n) => {
for (let i = 0; i < n; i++) {
num = n % 10; // get the last digit e.g 352 %10 = 2
reversed += num
result = parseInt(n / 10); // remove last digit e.g. parseInt(352/10) = 35
recurse(result);
if (result === 0) {
break;
}
}
return reversed;
};
return recurse(n);
}
console.log(reverseNum(1234));
console.log(reverseNum(1234));
But a more elegant method would be:
function reverseNum(n, str = String(n)) {
const thisDigit = str[str.length - 1];
const recursiveResult = str.length === 1 ? '' : reverseNum(str.slice(0, str.length - 1));
return Number(thisDigit + recursiveResult);
}
console.log(reverseNum(1234));
console.log(reverseNum(1234));
function reverse(number){
let index = 0 ;
let reversed = '';
let max = `${number}`.toString().length-1;
while(index <= max ){
reversed += `${number}`.charAt(max-index)
index ++;
}
return reversed;
}
console.log(reverse(546))
CertainPerformance has explained why your code wasn't working.
Here is another implementation, one I find reasonably simple:
const reverseNum = (n) =>
n < 10
? String(n)
: String (n % 10) + reverseNum (Math .floor (n / 10))
console .log (reverseNum (8675309))
Note that this returns a String rather than a Number. If we wanted to, we could make this a private function and make a public function one which called this and converted the result back into a number. But that would have the weird effect that reversing, say, 1000 would yield 1, since 0001 is simplified to 1. And that would mean that when you reverse again, you don't get anything like your original value. So I choose to keep with a String.
Of course if we're going to do String reversal, perhaps we're better off just using a String reversal function in the first place:
const reverseStr = (s) =>
s.length == 0
? ''
: reverseStr (s .slice (1)) + s [0]
const reverseNum = (n) =>
reverseStr (String(n))
console .log (reverseNum (8675309))
Or if we weren't interested in doing this recursively, we could just write the more common string reversal function:
const reverseStr = (s) =>
s .split ('') .reverse () .join ('')
const reverseNum = (n) =>
reverseStr (String (n))
console .log (reverseNum (8675309))

Recursion not properly running?

I'm practicing recursion, and am trying to use it to constantly add individual digits in a number until there is only 1 digit left.
Basically, if the number is 84, it becomes 8+4 = 12 which then becomes 1 + 2 = 3.
Below is my attempt on it. Not sure what I'm missing..
const weirdSum = (num) => {
let result = 0;
const split = num.toString().split('');
if(split.length > 1){
for(let i=0;i<split.length;i++){
result = result + (split[i]*1);
}
weirdSum(result); // pass result as argument, which will be split.
}
return result; // return result if split.length is 1
}
there are 2 mistakes, one you need to return weirdSum(result);
another you are returning result which is 0 you should return num
const weirdSum = (num) => {
let result = 0;
const split = num.toString().split('');
if(split.length > 1){
for(let i=0;i<split.length;i++){
result = result + (split[i]*1);
}
return weirdSum(result); // pass result as argument, which will be split.
}
return num; // return result if split.length is 1
}
console.log(weirdSum(84));
let weirdSum = num => {
const split = num.toString().split('');
if(split.length > 1){
const sum = split.reduce((acc, it) => parseInt(it) + acc, 0)
return weirdSum(sum);
}
return num;
}
console.log(weirdSum(84));
console.log(weirdSum(123456));
const weirdSum = (num) => {
let result = 0;
const split = num.toString().split('');
if(split.length > 1){
for(let i=0;i<split.length;i++){
result = result + (split[i]*1);
}
return weirdSum(result); // pass result as argument, which will be split.
}
return split[0]; // return result if split.length is 1
}
console.log(weirdSum(84))
I just changed your codes to works properly, I have no idea it is optimized or not.
You need ti return the split[0] when recursion stack ends not the result!
This function isn't anonymous but it solves your problem
function weirdSum(num) {
if(parseInt(num/10) == 0) {
return num;
}
var num1 = 0;
while(num != 0) {
var d = parseInt(num%10);
num1=num1+d;
num=parseInt(num/10);
}
return weirdSum(num1);
}
How it works ?
Any single digit number when divided by 10 gives 0 as quotient ( parsing to int is required ), function exists when this condition is met ( the first if ).
In the while loop I'm extracting digits of the number ( starting from the last digit ), when we divide a number by 10, the remainder is always the same as the last digit, then we are adding this to the new num ( num1 ).
In the last step of the while loop, we are shortening the number by removing is last digit by dividing it by 10 and repacing the old num1 by quoatient.
const weirdSum = num => {
// figure out the sum
const sum = [...num + ""].reduce((a, e) => a + (e - 0), 0);
// recurse if necessary
return sum < 10 ? sum : weirdSum(sum);
}
console.log(weirdSum(84));

Verify is Armstrong number with Javascript

I need to do a code to verify whether or not the entered number is an Armstrong number, but my code does not work for every number.
Could anyone tell me what am I missing? Are there any other ways to do this?
Thank you!
let e, x, d = 0;
let b = prompt("Enter a number");
x=b;
while (x > 0) {
e = x % 10;
x = parseInt(x/10);
d = d + (e*e*e);
}
if (b==d)
alert("given number is an armstrong number");
else
alert("given number is not an armstrong number");
<!DOCTYPE HTML>
<html>
<head>
<title>Armstrong</title>
</head>
<body>
</body>
</html>
I think the way you compute the result is wrong. According to Wikipedia, an Armstrong number, also called narcissistic number, has the following property:
[An Armstrong number] is a number that is the sum of its own digits each raised to the power of the number of digits.
You can compute it like this:
var number = prompt("Enter a number");
var numberOfDigits = number.length;
var sum = 0;
for (i = 0; i < numberOfDigits; i++) {
sum += Math.pow(number.charAt(i), numberOfDigits);
}
if (sum == number) {
alert("The entered number is an Armstrong number.");
} else {
alert("The entered number is not an Armstrong number.");
}
You can try this method, very easy to understand.
const armstrongNumber = (num) => {
const toArray = num.toString().split('').map(Number);
const newNum = toArray.map(a => {return a**3}).reduce((a, b) => a + b);
if(newNum == num){
console.log('This is an armstrong number');
}else{
console.log('This is not an armstrong number');
}
}
armstrongNumber(370);
//This is an armstrong number
Here is the solution to check Armstrong number without using Math Object.
function armstrongNum(number) {
const numberArr = String(number).split('');
const power = numberArr.length;
let TotalSum = numberArr.reduce((acc, cur) => {
return acc + (function(cur,power){
let curNum = Number(cur);
let product = 1;
while(power > 0) {
product *= curNum;
power --;
}
return product;
}(cur,power))
}, 0)
if (TotalSum === number) {
return true
}
return false
}
armstrongNum(153);
Here is an example of functional code for Armstrong Numbers.
<script>
function execute() {
var num1 = document.getElementById("Number1").value;
var num2 = document.getElementById("Number2").value;
var num3 = document.getElementById("Number3").value;
var concatNum = num1 + num2 + num3;
var num1Sqrt = num1 * num1 * num1;
var num2Sqrt = num2 * num2 * num2;
var num3Sqrt = num3 * num3 * num3;
if (num1Sqrt + num2Sqrt + num3Sqrt == concatNum) {
Answer.value = "The three integers you entered are Armstrong numbers.";
}
if (num1Sqrt + num2Sqrt + num3Sqrt != concatNum) {
Answer.value = "The three integers you entered are not Armstrong numbers.";
}
}
</script>
You first set your variables to what is entered, you then concatenate the string with the three integers.
You then square the three integers and set each value to a variable. You then have a basic check for equality, if the three squared values add up to your concatenated string then you have an Armstrong number.
This is how i solved mine:
function armstrong(num) {
var digits = num.toString().split('')
var realDigits = num
var a = 0
for (let i = 0; i < digits.length; i++){
digits[i] = Math.pow(digits[i], digits.length)
a += digits[i]
}
if (a == realDigits) {
console.log("Number is armstrong")
} else if (a != realDigits) {
console.log("Number is not armstrong")
}
}
armstrong(371)
//feel free to pass any value here
You can copy/paste and run this code at https://www.typescriptlang.org/play/
I hope this helps someone.
This works as well..
function isArmstrong (n) {
const res = parseInt(n, 10) === String(n)
.split('')
.reduce((sum, n) => parseInt(sum, 10) + n ** 3, 0);
console.log(n, 'is', res, 'Armstrong number')
return res
}
isArmstrong(153)
Here is another way to solve it.
let c = 153
let sum = 0;
let d = c.toString().split('');
console.log(d)
for(let i = 0; i<d.length; i++) {
sum = sum + Math.pow(d[i], 3)
}
if(sum == c) {
console.log("armstrong")
}
else {
console.log("not a armstrong")
}
Correct way to find Armstrong
var e, x, d = 0, size;
var b = prompt("Enter a number");
b=parseInt(b);
x=b;
size = x.toString().length;
while (x > 0) {
e = x % 10;
d = d + Math.pow(e,size);
x = parseInt(x/10);
}
//This is I solved without function
let num = prompt();
let num1 = num;
let sum = 0;
while(num > 0){
rem = num % 10;
sum = sum + Math.pow(rem, num1.length);
num = parseInt (num /10);
}
if (sum == num1) console.log("Armstrong");
else console.log("not Armstrong");
number is an Armstrong number or not.
let inputvalue=371
let spiltValue=inputvalue.toString().split('')
let output=0
spiltValue.map((item)=>output+=item**spiltValue.length)
alert(`${inputvalue} ${inputvalue==output? "is armstrong number" : "is not armstrong number"}`);
In order to get a Narcissistic/Armstrong number, you need to take the
length of the number as n for taking the power for summing the
value.
Here's another solution that works with an input >= 3 digits
(With Math.pow() each character is added as a number to the power of the array size)
const isArmstrongNumber = (n) => {
//converting to an array of digits and getting the array length
const arr = [...`${n}`].map(Number);
let power = arr.length;
const newNum = arr
.map((a) => {
return Math.pow(parseInt(a), power);
})
.reduce((a, b) => a + b);
return newNum == n;
};
console.log("Is it Armstrong? " + isArmstrongNumber(370));
console.log("Is it Armstrong? " + isArmstrongNumber(123));
console.log("Is it Armstrong? " + isArmstrongNumber(1634));
You can try for This, May this help for you:
<!DOCTYPE HTML>
<html>
<head>
<title>Armstrong</title>
</head>
<body>
</body>
</html>
<script>
var z,e,x,d=0;
var b=prompt("Enter a number");
x=parseInt(b);
while(x>0) //Here is the mistake
{
e=x%10;
x=parseInt(x/10);
d=d+(e*e*e);
console.log("d: "+d+" e: "+e);
}
if(parseInt(b)==d){
alert("given no is amstrong number");
}
else {
alert("given no is not an amstrong number");
}
</script>

Can I perform multiplication without using the multiplication operator "*" in JavaScript

I need to multiply two numbers in JavaScript, but I need to do without using the multiplication operator "*". Is it possible?
function a(b,c){
return b*c;
} // note:need to do this without the "*" operator
Yes. Because multiplication is just addition done multiple times. Also have meaningful signatures for methods instead of using single alphabets.
function multiply(num, times){
// TODO what if times is zero
// TODO what if times is negative
var n = num;
for(var i = 1; i < times; i++)
num += n; // increments itself
return num;
}
a=(b,c)=>Math.round(b/(1/c))
You need to be able to handle negatives and zeros. Other above answers don't help here. There are different ways. One relatively messy way could be ifs:
function multiply(num1, num2) {
var sum = 0;
for (var i = 0; i < Math.abs(num2); i++) {
sum += num1;
}
if (num1 < 0 && num2 < 0) {
return Math.abs(sum);
} else if (num1 < 0 || num2 < 0 ) {
return -sum;
} else {
return sum;
}
}
There is another simpler mathematical approach. Let's do this in C++:
double mult(double a, double b) {
return exp(log(a) + log(b));
}
The log() function in C++ returns the natural logarithm (base-e logarithm) of the argument passed in the parameter. (arguments can be any numeric type)
The exp() function in C++ returns the exponential (Euler's number) e (or 2.71828) raised to the given argument.
When you simplify the above statement, you eventually end up with a * b, but still there is no * sign.
*You need make sure both a and b are positive, otherwise you will get nan :(
Here is a math trick
function multiply(num1, num2) {
return num1/(1/num2);
}
console.log(multiply(5,22))
I think this can be solved using recursion. Sorry for the improper indentations.
We are given 2 numbers to multiply and multiplying m with n simply means adding m, n times.
if n becomes 0, return 0. This is our base case.
else
return m + multi(m,n-1)
we are returning m every time, because we need to add m up to n times
In every call we are decreasing the n's value so as the n becomes 1, we'll call it for the last time.
function multi (int m, int n){
if(n === 0)
return 0;
return m + multi(m,n-1);
}
repeat() method of string can be used to find multiplication of two numbers.
var a = 3;
var b = 4;
var res = "1".repeat(a).repeat(b).length;
console.log(res)
log: 12
It is repeating c, a times=> 'ccc' and then whole string b times=> 'cccccccccccc', length of the final string will be a*b;
This is similar to loop approach.
This approach is limited to positive and integer numbers only.
function multiply(num1, num2) {
let num = 0;
// Check whether one or both nums are negative
let flag = false;
if(num1 < 0 && num2 < 0){
flag = true;
// Make both positive numbers
num1 = Math.abs(num1);
num2 = Math.abs(num2);
}else if(num1 < 0 || num2 < 0){
flag = false;
// Make the negative number positive & keep in num2
if(num1 < 0){
temp = num2;
num2 = Math.abs(num1);
num1 = temp;
}else{
num2 = Math.abs(num2);
}
}else{
flag = true;
}
let product = 0;
while(num < num2){
product += num1;
num += 1;
}
// Condition satisfy only when 1 num is negative
if(!flag){
return -product;
}
return product;
}
console.log(multiply(-2,-2));
function multiple(a, b) {
let sum = 0;
for (let i = 0; i < Math.abs(b); i++) {
sum += Math.abs(a);
}
if (a < 0 && b < 0) {
return Math.abs(sum);
} else if (a < 0 || b < 0 ) {
return -sum;
} else {
return sum;
}
}
Is this from some programming puzzle or interview question? :)
Since multiplication is repeated addition, you probably want a loop which adds one of the factors to the result for each count in the other factor.

Categories