Number Addition Coderbyte Solution

0

 Have the function NumberSearch(str) take the str parameter, search for all the numbers in the string, add them together, then return that final number. 

For example: if str is "88Hello 3World!" the output should be 91. You will have to differentiate between single-digit numbers and multiple-digit numbers like in the example above. So "55Hello" and "5Hello 5" should return two different answers. Each string will contain at least one letter or symbol.



Array Addition Coderbyte Solution Java


import java.util.Scanner;

public class NumberAddition {
final String NUMBERS = "0123456789";

int NumberAddition(String str) {
int sum = 0;

char[] chars = str.toCharArray();
StringBuilder number = new StringBuilder("");
for (int i = 0; i < chars.length; i++) {
if (NUMBERS.indexOf(chars[i]) != -1) {
number.append(chars[i]);

if (i == chars.length - 1) {
sum += Integer.valueOf(number.toString());
}
} else if (number.length() != 0) {
sum += Integer.valueOf(number.toString());
number.setLength(0);
}
}

return sum;
}

public static void main (String[] args) {
Scanner s = new Scanner(System.in);
NumberAddition c = new NumberAddition();
System.out.print(c.NumberAddition(s.nextLine()));
}
}


Array Addition Coderbyte Solution JavaScript

Using the JavaScript language, have the function NumberSearch(str) take the str parameter, search for all the numbers in the string, add them together, then return that final number. 

For example: if str is "88Hello 3World!" the output should be 91. You will have to differentiate between single digit numbers and multiple digit numbers like in the example above. So "55Hello" and "5Hello 5" should return two different answers. Each string will contain at least one letter or symbol.  


function NumberAddition(str) {

var tot = 0;
str = str.replace(/[^0-9\.]+/g," ").split(" ");
for (var i = 0; i < str.length; i++) {
tot += Number(str[i]);
}
return tot;
}

Explanation

I only want numbers in the string so I am using RegExp to remove everything that is not a number. Then convert that to an array. Loop thru each number in the array and add tot to get the answer.

Disclaimer: The above Problem is generated by Coderbyte but the Solution is provided by ShouterFolk.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !