NC_1_BIGDATA_ADD
package org.example.interview.practice; import java.util.Stack; /** * @author xianzhe.ma * @date 2021/9/2 */ public class NC_1_BIGDATA_ADD { public static String solve (String s, String t) { // write code here int size1 = s.length(); int size2 = t.length(); Stack<String> stack = new Stack<>(); char[] charArray1 = s.toCharArray(); char[] charArray2 = t.toCharArray(); int i = size1 - 1; int j = size2 - 1; int remainder = 0; int temp = 0; while (i >= 0 && j >= 0) { char value1 = charArray1[i]; char value2 = charArray2[j]; temp = Integer.valueOf(String.valueOf(value1)) + Integer.valueOf(String.valueOf(value2)); if (temp + remainder > 9) { temp = (temp + remainder) %10; remainder = 1; } else { temp = temp + remainder; remainder = 0; } stack.push(String.valueOf(temp)); i--; j--; } //循环结束,且两组字符串都处理完了,查看有没有进位 if (i <0 && j < 0) { if (remainder == 1) { stack.push(String.valueOf(remainder)); } } //某一个字符有剩余继续处理 if ( i >=0) { String s1 = s.substring(0,i+1); if (remainder > 0) { char[] arr1 = s1.toCharArray(); int size = s1.length(); Integer temp1 = 0; for (int k=size-1;k>=0;k--) { temp1 = Integer.valueOf(String.valueOf(arr1[k])); temp1 = temp1 + remainder; remainder = temp1 / 10; temp1 = temp1 % 10; stack.push(String.valueOf(temp1)); } if (remainder > 0) { stack.push(String.valueOf(remainder)); } } else { stack.push(s1); } } //某一个字符有剩余继续处理 if ( j >=0) { String s1 = t.substring(0,j+1); if (remainder > 0) { char[] arr1 = s1.toCharArray(); int size = s1.length(); Integer temp1 = 0; for (int k=size-1; k>=0; k--) { temp1 = Integer.valueOf(String.valueOf(arr1[k])); temp1 = temp1 + remainder; remainder = temp1 / 10; temp1 = temp1 % 10; stack.push(String.valueOf(temp1)); } if (remainder > 0) { stack.push(String.valueOf(remainder)); } } else { stack.push(s1); } } StringBuilder strBuilder = new StringBuilder(); while (!stack.isEmpty()) { strBuilder.append(stack.pop()); } return strBuilder.toString(); } public static void main (String[] args) { String s1 = "733064366"; String s2 = "459309139"; System.out.println(solve(s1, s2)); String newStr = String.join("-", s1, s2); System.out.println(newStr); } }