Add String
public String addDecimal(String num1, String num2) {
String[] nums1 = num1.split("\\.");
String[] nums2 = num2.split("\\.");
String[] res1 = padding(nums1[0], nums2[0], 'L');
String[] res2 = padding(nums1[1], nums2[1], 'R');
return addStrings(res1[0] + "." + res2[0], res1[1] + "." + res2[1]);
}
public String[] padding(String str1, String str2, char direction) {
String maxStr = str1.length() > str2.length() ? str1 : str2;
String minStr = str1.length() > str2.length() ? str2 : str1;
if (direction == 'L') {
int i = maxStr.length() - 1, j = minStr.length() - 1;
while (i >= 0 || j >= 0) {
if (j < 0) {
minStr = "0" + minStr;
}
i--;
j--;
}
} else {
int i = 0, j = 0;
while (i < maxStr.length() || j < minStr.length()) {
if (j >= minStr.length()) {
minStr = minStr + "0";
}
i++;
j++;
}
}
return new String[] { minStr, maxStr };
}
public String addStrings(String num1, String num2) {
if (num1 == null || num2 == null) {
return "";
}
StringBuilder res = new StringBuilder();
char[] n1 = num1.toCharArray();
char[] n2 = num2.toCharArray();
int i = n1.length - 1;
int carry = 0;
while (i >= 0 || carry == 1) {
if (n1[i] == '.') {
i--;
res.append(".");
continue;
}
int d1 = n1[i] - '0';
int d2 = n2[i] - '0';
int total = (d1 + d2 + carry);
int digit = total % 10;
carry = total / 10;
res.append(String.valueOf(digit));
i--;
}
return res.reverse().toString();
}