Sum of Digits using tostring and number methods javascript - javascript

Can someone explain what I am doing wrong in this problem? I want to add the sum of the num variable using toString and Number methods. I first turn num into the string num = '12345'. Then I loop through string, turn it into a number and add it to the sum.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = 0;
num.toString();
for(var i = 0; i < num.length; i++){
sumOfDigits += Number(num[i]);
}
return sumOfDigits;
}

You're not assigning the result of num.toString() to anything.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = 0;
num = num.toString();
for (var i = 0; i < num.length; i++) {
sumOfDigits += Number(num[i]);
}
return sumOfDigits;
}
console.log(sumDigits(num));

I believe you can use this one :
var num = 12345;
function sumDigits(num) {
//empty variable
var str;
//check type of the incoming value
(typeof num == "string") ? str = num : str = num.toString();
//this is the same with above if you don't know how to use short handed if else
/*
if(typeof num == "string"){
str = num;
} else {
str = num.toString();
}
*/
//Array's split Method and a variable which u have create already
var arr = str.split(''), sumOfDigits = 0;
for(var i in arr){
//You should use parseInt() method.
sumOfDigits += parseInt(arr[i]);
}
//return the sum of the digits
return sumOfDigits;
};
console.log(sumDigits(num));
If you have future problems please first search a bit then write here :)

Updated:
You can use split, map and reduce to split the array, map it to integers, then use a reduce function to sum the integers.
You could eliminate the map if you want to move parse into the reduce, but I like to keep the steps separate.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = num
.toString()
.split('')
.map(function(n) { return parseInt(n);})
.reduce(function(acc, val) {
return acc + val;
},
0
);
return sumOfDigits;
}
var sum = sumDigits(num);
console.log(sum)

Related

can anyone figure out the bug in my code?

The function is supposed to solve the following problem, but there is something wrong in it.
The problem:
Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number.
function repeatStringNumTimes(str, num) {
var result = '';
for(let i = 0; i < num; i++){
result += 'str';
}
return result;
}
repeatStringNumTimes("abc", 3);
two problems. first 'str' will give you a literal. you want the variable str. second, once you have the result you need to display it.
function repeatStringNumTimes(str, num) {
var result = '';
for(let i = 0; i < num; i++){
result += str;
}
return result;
}
var result = repeatStringNumTimes("abc", 3);
console.log(result);
you will have to add the old string to the new one and don't forget the space between them
function repeatStringNumTimes(str, num) {
var result = '';
for(let i = 0; i < num; i++){
result = result + str + ' ';
}
return result;
}
repeatStringNumTimes("abc", 3);
First you're not returning if the num is not positive. Second, it should be str and not 'str' if you want to repeat the variable.
function repeatStringNumTimes(str, num) {
var result = '';
if (num < 1) return; //return if num is not postive
for(let i = 0; i < num; i++){
result += str;
}
return result;
}
var res = repeatStringNumTimes("abc", 3);
console.log(res)

How to Split String and get Number form it?

I have one string "I_am_125_developer_25" and want result 150 means 125+25 using javascript
var a = "I_am_125_developer_25";
I tried following solution
for(var i = 0; i<= a.length; i++)
{
if(typeof a[i] == Number)
{
var c = a[i]; console.log(c);
}
}
Here I need to add two numbers from string need to check whether it is number or not.
Try
"I_am_125_developer_25".match(/\d+/g).reduce( (a,b) => Number(a) + Number(b) )
Explanation
Match numbers, get the array ["125", "25"]
Reduce the array by adding the converted (to Number) array items (reference here)
Edit
If you also want to support the scenarios like "I_am_1x5_developer_25", then make it
"I_am_1x5_developer_25".split(/_/).filter( s => !isNaN(s) ).reduce( (a,b) => Number(a) + Number(b) );
Explanation
split by _
filter out non-numeric values
Reduce the array by adding the converted (to Number) array items
function getSumFromString(str) {
var total = 0;
str.split('_').forEach(function(e){
var num = parseInt(e);
if(num) {
total +=num;
}
});
return total;
}
getSumFromString('I_am_125_developer_25');
I got the solution
var total = 0;
for(var i=0; i<=arr.length; i++){
if(!isNaN(arr[i])) {
total+=Number(arr[i]);
}
}
console.log(total);
A simple solution would be to split the string and make it an array, loop through it, verify which are numbers using isNaN() method and sum up the numbers:
var a = "I_am_125_developer_25";
a = a.split('_');
var sum = 0;
for(var i = 0; i < a.length; i++){
if(!isNaN(a[i])){
sum += parseInt(a[i]);
}
}
console.log(sum);
Try this:
var string = "I_am_125_developer_25";
var regex = /(\d+)/g;
var numArray = string.match(regex);
var sum=0;
for (var i=0;i<numArray.length;i++){
sum+=parseInt(numArray[i]);
}
console.log(sum);

Splitting Numbers and adding them all - JavaScript

I have a function that returns the sum of all its digits For both POSITIVE and NEGATIVE numbers.
I used split method and converted it to string first and then used reduce to add them all. If the number is negative, the first digit should count as negative.
function sumDigits(num) {
var output = [],
sNum = num.toString();
for (var i = 0; i < sNum.length; i++) {
output.push(sNum[i]);
}
return output.reduce(function(total, item){
return Number(total) + Number(item);
});
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
Instead of returning the sum, it returned 4592 -1264
Am I doing it right or do I need to use split function? Or is there any better way to do this?
Sorry newbie here.
I think you'll have to treat it as a string and check iterate over the string checking for a '-' and when you find one grab two characters and convert to an integer to push onto the array. Then loop over the array and sum them. Of course you could do that as you go and not bother pushing them on the array at all.
function sumDigits(num) {
num = num + '';
var output = [];
var tempNum;
var sum = 0;
for (var i = 0; i < num.length; i++) {
if (num[i] === '-') {
tempNum = num[i] + num[i + 1];
i++;
} else {
tempNum = num[i];
}
output.push(parseInt(tempNum, 10));
}
for (var j = 0; j < output.length; j++) {
sum = sum + output[j];
}
return sum;
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4

How to make characters in a string repeat using Javascript?

How can I make individual characters within a string repeat a given amount of times?
That is, how do I turn "XyZ" into "XXXyyyZZZ"?
Try this:
var foo = 'bar';
function makeString(str, repeat) {
var str = Array.prototype.map.call(str, function(character) {
var nascentStr = '';
while (nascentStr.length < repeat) {
nascentStr += character;
}
return nascentStr;
}).join('');
return str;
}
alert(makeString(foo, 3));
You'll need to use a combination of a few functions. First you'll need to split the string into individual characters:
var charArray = "XyZ".split('');
Once you have it split up, you can use a combination of the .map function and a nifty little trick of javascript Array.
var someMultiplier = 5;
var duplicatedArray = charArray.map(function(char) {
return Array(someMultiplier).join(char);
});
At that point, you have an array of strings that have the duplicate letters, and you can combine them back with .join
var dupString = duplicatedArray.join('');
dupString === "XXXXXyyyyyZZZZZ
Sounds straight forward. You can run this in your browser's console:
var my = 'XyZ';
function repeat(str, times) {
var res = '';
for (var i in str) {
var char = str[i];
for (var j=0; j < times; j++) {
res += char;
}
}
return res;
}
var his = repeat(my, 3);
console.log(his);
you have not mentioned what will happen if input will be like xyxzy. Assuming it will be xxxyyxxxzzzyyy
// function takes input string & num of repitation
function buildString(input, num) {
var _currentChar = ""; // Final output string
for (var m = 0; m < input.length; m++) {
//call another function which will return XXX or yyy or zzz & then finally concat it
_currentChar += _repeatString((input.charAt(m)), num);
}
}
// It will return XXX or yyy or ZZZ
// takes individual char as input and num of times to repeat
function _repeatString(char, num) {
var _r = "";
for (var o = 0; o < num; o++) {
_r += char;
}
return _r
}
buildString('XyZ', 3)
jsfiddle for Example
function repeatStringNumTimes(str, num) {
let valueCopy = str
if (num > 0) {
for (var i = 0; i < num - 1; i++) {
valueCopy = valueCopy.concat(str)
}
} else {
valueCopy = ""
}
return valueCopy;
}
repeatStringNumTimes("abc", 3);
These days can be done a lot easier:
const repeater = (str, n) => [...str].map(c => c.repeat(n)).join('');
alert(repeater('XyZ', 3));

Trying to square every digit of a number, but my algorithm is not working?

I'm trying to square every digit of a number;
for example:
123 should return 149
983 --> 81649 and so on
I messed it up somewhere in the following Javascript code and I'm looking for some guidance.
function splitNumber(num){
var arr = [];
while(num>0){
var c = num%10;
arr[arr.length]=c;
num=num/10;}
return arr;
}
function squareArrToNumber(arr){
var c = 0;
for(var i=arr.length-1;i>=0;i--){
arr[i]=arr[i]^2;
if(arr[i]^2>10)
c = c*100+arr[i];
else
c = c*10+arr[i];
}
return c;
}
function squareDigits(num){
squareArrToNumber(splitNumber(num));
}
Try out this code
function numToSqr(num){
var i, sqr=[],n;
num = num.toString();
for(i=0;i<num.length;i++){
n = Number(num[i]);
sqr.push(n*n);
}
return Number(sqr.join(""));
}
There are multiple things wrong with your code, starting with an overcomplication to split a string of numbers into its consituant characters just use .splt(""):
var str = "123";
var arr = str.split("");
for(var i = 0;i<arr.length;i++)
alert(arr[i]);
Next, the code num ^ 2 does not square a number. To do a square, simply multiply a number by itself (num * num)
This leaves us with a rather simple solution
function splitNumber(num){
return num.split("");
}
function joinArray(arr){
return arr.join("");
}
function squareArrToNumber(arr){
var newArr = [];
for(var i=0;i<arr.length;i++){
newArr.push(arr[i] * arr[i]);
}
return joinArray(newArr);
}
function squareDigits(num){
return squareArrToNumber(splitNumber(num));
}
alert(squareDigits("123"));
alert(squareDigits("983"));
Here is how I would do such a thing:
var num = 123;
var numArray = num.toString().split("");
var result = "";
for(var i = 0; i < numArray.length; i++){
result += parseInt(numArray[i]) * parseInt(numArray[i]);
}
function squareNum(number) {
var array = [];
// Split number into an array of numbers that make it up
array = String(number).split('');
for (let i = 0; i < array.length; i++) {
// Take each number in that array and square it (in place)
// Also can be done with forEach depending on what es version you're targetting
array[i] = Math.pow(array[i], 2);
}
// combine and return the elements of the array
return Number(array.join(''));
}
squareNum(123);
squareNum(983);
try this example
function squareDigits(n) {
return +(n.toString().split('').map(val => val * val).join(''));
}
console.log(squareDigits(4444));
here + sign is convert the string into an integer.
if(arr[i]^2>10)
should be
if(arr[i]>10)
And, as #Luaan noted, it should be
arr[i] *= arr[i]

Categories