415. Add Strings

这题其实写起来有点烦的 注意index不要超,使用i作count会比较方便。

class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int len1 = num1.length();
        int len2 = num2.length();
        int longer = len1>len2?len1:len2;
        int shorter = longer==len1? len2:len1;
        int carry = 0;
        // use i for count not index 
        for(int i = 0;i<shorter;i++)
        {
            int n1 = (int)(num1.charAt(len1-1-i)-'0');
            int n2 = (int)(num2.charAt(len2-1-i)-'0');
            int num = (n1+n2+carry)%10;
            carry=(n1+n2+carry)/10;
            sb.insert(0,num);
        }
        for(int i = 0;i<longer-shorter;i++)
        {
            if(len1==longer)
            {
                 int n1 = (int)(num1.charAt(len1-shorter-1-i)-'0');
                 int num = (n1+carry)%10;
                 carry=(n1+carry)/10;
                System.out.println(num);
                 sb.insert(0,num);
            }
            else
            {
              int n2 = (int)(num2.charAt(len2-shorter-1-i)-'0');
              int num = (n2+carry)%10;
              carry=(n2+carry)/10;
              sb.insert(0,num);
            }
        }
        if(carry==1)
            sb.insert(0,1);
        return sb.toString();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,351评论 0 33
  • 问题: Given two non-negative numbers num1 and num2 represen...
    Cloudox_阅读 1,560评论 0 0
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,632评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,464评论 19 139
  • 几年过去了 当初的青春已变成回忆,留在青春的美好已不复存在,有时候会怀念自己当初对你的爱,对你的付出,那是一份单纯...
    李洛溪阅读 851评论 0 0