In: Computer Science
Given a string like the following one in Java "123+45+678", how can I pull out the characters that make up the separate integers and add them together. I'm not allowed to use parseInt().
So for this one I would need to add 123 + 45 + 678 to get the total(846)
Program:
public class Main
{
public static int convertStr(String str)
{
// Initializing a variable
int num = 0;
// Returns length of the given string
int len = str.length();
// Iterate till length of the string
for(int x = 0; x < len; x++)
// Subtract 48 from the current digit
// Converting string to number
num = num * 10 + ((int)str.charAt(x) - 48);
// Returns number
return num;
}
public static void main(String[] args) {
String givenStr = "123+45+678";
// Splitting the given string based on +
String[] splittedStr = givenStr.split("\\+");
// Converting the strings to intergers and adding them
int total = convertStr(splittedStr[0]) + convertStr(splittedStr[1]) + convertStr(splittedStr[2]);
// Printing the output as total
System.out.println("Total: "+splittedStr[0]+" + "+splittedStr[1]+" + "+splittedStr[2]+" = "+total);
}
}
Output: