题解 | #高精度整数加法#

高精度整数加法

http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6

思路

  • 选一个更长的字符串长度进行 for 循环
  • 每次从最后一位开始相加,处理好进位
  • 相加后作为结果放在最后
  • 循环结束,检查是否有进位,有则字符头加 1
  • 输出

代码

while(str1 = readline()) {
  const str2 = readline();
  let result = "";
  let sub=false;
  const len = Math.max(str1.length, str2.length);
  for(let i=1;i<=len;i++) {
    let temp = ~~str1[str1.length-i] + ~~str2[str2.length-i] + Number(sub);
    if(temp > 9) {
      sub = true;
      temp = temp - 10;
    } else {
      sub = false;
    }
    result = `${temp}`+result
  }
  if(sub) result = '1' + result
  console.log(result);
}
全部评论

相关推荐

神哥不得了:首先我就是在成都,成都的互联网格外的卷,如果是凭现在的简历的话很难找到大厂,建议再添加一个高质量的项目上去,另外专业技能的话最好是超过每一条的一半
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务