1、NC1 大数加法
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 计算两个数之和 * @param s string字符串 表示第一个整数 * @param t string字符串 表示第二个整数 * @return string字符串 */ public String solve (String s, String t) { // write code here } }
实现
// 没不出来,这个不对 import java.util.*; public class Solution { public String solve (String s, String t) { // long num1 = Long.parseLong(s); // long num2 = Long.parseLong(t); // return "" + (num1 + num2); String res = ""; int flag = 0; for(int i=s.length()-1, j=t.length()-1; i>=0 && j>=0; i--, j--){ int numS = s.charAt(i); //自动转换 int numT = s.charAt(j); if(numS + numT + flag >= 10){ flag = 1; res += (numS + numT + flag) / 10; }else{ flag = 0; res += (numS + numT); } } System.out.println(res); return res; } }View Code
参考
import java.math.BigInteger; import java.util.*; public class Solution { public String solve (String s, String t) { BigInteger bigInteger1 = new BigInteger(s); BigInteger bigInteger2 = new BigInteger(t); return bigInteger1.add(bigInteger2).toString(); } }
import java.util.*; public class Solution { public String solve (String s, String t) { int sum = 0; StringBuilder result = new StringBuilder(); int si = s.length() - 1; int ti = t.length() - 1; while (si >= 0 || ti >= 0) { if (si >= 0) { sum += s.charAt(si) - '0'; si--; } if (ti >= 0) { sum += t.charAt(ti) - '0'; ti--; } result.append(sum % 10); sum = sum >= 10 ? 1 : 0; } if (sum > 0) { result.append(sum); } return result.reverse().toString(); } }
import java.util.*; public class Solution { public String solve (String s, String t) { int len1 = s.length(); int len2 = t.length(); int max = len1; if (max < len2) { max = len2; s = padding(s, max); } else { t = padding(t, max); } StringBuilder sb = new StringBuilder(max + 1); int add = 0; for (int i=max-1; i>=0; i--) { int num1 = s.charAt(i) - '0'; int num2 = t.charAt(i) - '0'; int sum = num1 + num2 + add; sb.append(sum % 10); add = sum / 10; } if (add > 0) { sb.append(add); } return sb.reverse().toString(); } private String padding(String s, int max) { if (s.length() == max) { return s; } StringBuilder sb = new StringBuilder(max); int gap = max - s.length(); while (gap > 0) { sb.append('0'); gap--; } sb.append(s); return sb.toString(); } }
2、NC127 最长公共子串
import java.util.*; public class Solution { /** * longest common substring * @param str1 string字符串 the string * @param str2 string字符串 the string * @return string字符串 */ public String LCS (String str1, String str2) { // write code here } }