目录
大数加法
访问量:944

一、简介

以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。

字符串仅由'0'~‘9’构成

要求: 空间复杂度 O(1)(仅在传入字符串上操作),时间复杂度 O(n)

二、实现

思路:数字字符串中每一位,都是由0~9之间的字符组成,进而转为为字符的加减法,0~9直接的字符ascii码值如下:

字符ASCII码
048
149
250
351
452
553
654
755
856
957


A-Z对应ascii码 65~90

a-z 对应ascii码为97~122

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 计算两个数之和
 * @param s string字符串 表示第一个整数
 * @param t string字符串 表示第二个整数
 * @return string字符串
*/
func solve( s string ,  t string ) string {
 if s == "" {
  return t
 }
 if t == "" {
  return s
 }
 
 // write code here
 index1 := len(s) -1
 index2 := len(t) -1
 
 res := ""
 flag := uint8(0)
 for index1 >=0 || index2 >= 0 {
  var totalByte byte
  if index1 < 0 {
   totalByte = t[index2] + flag
   index2 = index2 - 1
  }else if index2 < 0 {
   totalByte = s[index1] + flag
   index1 = index1 - 1
  } else {
   totalByte = s[index1] + t[index2] - 48  + flag
   index2 = index2 - 1
   index1 = index1 - 1
  }
 
  // 将进位设置为0
  flag = 0
  // 超过9
  if totalByte > 57 {
   totalByte = totalByte - 10
   flag = flag +1
  }
 
  res = string(totalByte) + res
 }
 
 if flag != 0 {
  flag = flag + 48
  res = string(flag) + res
 }
 
 return res
}