Sum all the digits of a number Javascript
Basically you have two methods to get the sum of all parts of an integer number.
With numerical operations
Take the number and build the remainder of ten and add that. Then take the integer part of the division of the number by 10. Proceed.
var value = 2568,
sum = 0;
while (value) {
sum += value % 10;
value = Math.floor(value / 10);
}
console.log(sum);
Find Sum From String of Numbers
Here is an easy way to do it.
String string =
"This12is mix of 3 characters 45spaces and numbers 67";
- initialize sum to
0
; - loop thru all the characters
- Check that the character is a digit
- if so, subtract
'0'
and sum the result.
int sum = 0;
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (Character.isDigit(c)) {
sum = sum + c - '0';
}
}
Prints
28
About subtracting '0'
ASCII and Unicode characters are binary values that are encoded for display on some output device. This includes digits. However, digits are not in proper format for numeric computations so they need to be converted to their numeric binary format. The easiest way is to subtract decimal 48 (which is the encoded representation for the digit 0) from each digit prior to summing them. For larger numbers like "29929" Integer.parseInt()
can be used. Internally it does similar processing of the individual digits as previously described.
Display the sum of digits in a number entered by the user
This is a very common mistake. char
is really just a number - the encoding value of the character represented by the char
. When you do Convert.ToInt32
on it, it sees the char
as a number and says "alright let's just convert this number to 32 bits and return!" instead of trying to parse the character.
"Wait, where have I used a char
in my code?" you might ask. Well, here:
Convert.ToInt32(num[count]) // 'num[count]' evaluates to 'char'
To fix this, you need to convert the char
to a string
:
nums[count] = Convert.ToInt32(num[count].ToString());
^^^^^^^^^^^^^^^^^^^^^
Now you are calling a different overload of the ToInt32
method, which actually tries to parse the string.
Related Topics
How to Add Anchor Tag to a Url from Text Input
How to Implement Pagination in PHP
PHP Read_Exif_Data and Adjust Orientation
Why Are Functions and Methods in PHP Case-Insensitive
Special Characters in PHP/Mysql
How to Solve Incompatible with SQL_Mode=Only_Full_Group_By in Laravel Eloquent
Mysql_Num_Rows(): Supplied Argument Is Not a Valid MySQL Result Resource
PHP Artisan Make:Auth Command Is Not Defined
Passing a Variable from One PHP Include File to Another: Global VS. Not
Get Date Range Between Two Dates Excluding Weekends
Custom Pagination View in Laravel 5
How to Do Error Logging in Codeigniter (Php)
Destroy or Unset Session When User Close the Browser Without Clicking on Logout