🚩传送门:牛客题目

🍗鸡腿知识点:

  1. BigInteger bigInteger1 = new BigInteger(s);
  2. StringBuffer res=new StringBuffer(); res.reverse().toString() 自带反转函数

题目

以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。
数据范围:[NC]1. 大数加法 【大数类型、字符串流的反转函数】 - 图1,字符串仅由0 ~ 9构成

要求: 空间复杂度 [NC]1. 大数加法 【大数类型、字符串流的反转函数】 - 图2 仅在传入字符串上操作),时间复杂度 [NC]1. 大数加法 【大数类型、字符串流的反转函数】 - 图3

解题思路:大数类型

整理代码

  1. public class Solution {
  2. public String solve (String s, String t) {
  3. BigInteger bigInteger1 = new BigInteger(s);
  4. BigInteger bigInteger2 = new BigInteger(t);
  5. return bigInteger1.add(bigInteger2).toString();
  6. }
  7. }

解题思路:加法模拟

我的代码

  1. public class Solution {
  2. public String solve (String s, String t) {
  3. int s1=s.length()-1;
  4. int t1=t.length()-1;
  5. int sum=0;
  6. //1.使用 StringBuffer 是因其自带 reverse 函数
  7. StringBuffer res=new StringBuffer();
  8. while(s1>=0||t1>=0){
  9. if(s1>=0)
  10. sum+=(s.charAt(s1--)-'0');
  11. if(t1>=0)
  12. sum+=(t.charAt(t1--)-'0');
  13. res.append(sum%10);
  14. sum/=10;
  15. }
  16. return sum>0?(res.append(sum%10)).reverse().toString():res.reverse().toString();
  17. }
  18. }