go解题答案

  • 时间复杂度O(n)

  • 思路概括:小学加法

  • 思路核心:
    1、循环长的数
    2、每位相加,注意进位
    3、-"0" 将字符数组转成对应数

    func solve( s string ,  t string ) string {
      // write code here
    
      sLen := len(s)
      tLen := len(t)
    
      // let sLen<tLen 为了下面遍历方便,找到最大的长度
      if sLen > tLen {
          sLen,tLen = tLen,sLen
          s,t = t,s
      }
    
      ret := make([]byte, tLen + 1) // 可能进一位,所以n+1
    
      carry := 0 //进位符
      for i:=0; i< tLen; i++ { // 循环长的数
    
          longN := int(t[tLen-i-1]-'0') // 减0是因为 字符和 数字正好差48,而“0” byte值是 48
          shortN := 0
          if sLen-i-1 >= 0 {
              shortN = int(s[sLen-i-1] - '0')
          }
    
          result := longN + shortN + carry // 这里的carry是上一次可能的进位
          carry = result / 10 //计算本次进位
          result = result % 10 //计算本次个位
          ret[tLen-i] = byte(result + '0')
      }
    
      if carry == 1 {
          ret[0] = '1'
          return string(ret)
      }
    
      return string(ret[1:])
    }

    如果有帮助请点个赞哦, 更多文章请看我的博客

    题主背景

  • 从业8年——超级内卷500Q技术经理——目前专注go和微服务架构