Java Exercises: Given two non-negative integers represented as string, return their sum
Java Basic: Exercise-189 with Solution
Write a Java program to given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Pictorial Presentation:

Sample Solution:
Java Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
String n1 = "123";
String n2 = "456";
System.out.println("'" + n1 + "'" + " + " + "'" + n2 + "'" + " = " + addStrings(n1, n2));
}
public static String addStrings(String n1, String n2) {
int[] x = str_num(n1);
int[] y = str_num(n2);
int[] sum = new int[Math.max(x.length, y.length) + 1];
int z = 0;
int index = sum.length - 1;
int i = 0;
int j = 0;
while (index >= 0) {
if (i < x.length) {
z += x[i++];
}
if (j < y.length) {
z += y[j++];
}
sum[index--] = z % 10;
z /= 10;
}
StringBuilder sb = new StringBuilder(sum.length);
for (i = (sum[0] == 0 ? 1 : 0); i < sum.length; ++i) {
sb.append(sum[i]);
}
return sb.toString();
}
private static int[] str_num(String num) {
char[] digits = num.toCharArray();
int[] number = new int[digits.length];
int index = number.length - 1;
for (char digit: digits) {
number[index--] = digit - '0';
}
return number;
}
}
Sample Output:
'123' + '456' = 579
Flowchart:

Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to find all the start indices of a given string's anagrams in another given string.
Next: Write a Java program to find the missing string from two given strings.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to remove leading zeros from alphanumeric text?
Regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0" to a blank string).
s.replaceFirst("^0+(?!$)", "")
The ^ anchor will make sure that the 0+ being matched is at the beginning of the input. The (?!$) negative lookahead ensures that not the entire string will be matched.
Test harness:
String[] in = { "01234", // "[1234]" "0001234a", // "[1234a]" "101234", // "[101234]" "000002829839", // "[2829839]" "0", // "[0]" "0000000", // "[0]" "0000009", // "[9]" "000000z", // "[z]" "000000.z", // "[.z]" }; for (String s : in) { System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]"); }
Ref: https://bit.ly/2Qdcl8a
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises