• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Add Strings

Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

 

 1 public class Solution {
 2     public String addStrings(String num1, String num2) {
 3         StringBuffer res = new StringBuffer();
 4         int i = num1.length()-1;
 5         int j = num2.length()-1;
 6         int carry = 0;
 7         while (i>=0 || j>=0 || carry!=0) {
 8             int sum = 0;
 9             if (i >= 0) {
10                 sum += (int)(num1.charAt(i) - '0');
11                 i--;
12             }
13             if (j >= 0) {
14                 sum += (int)(num2.charAt(j) - '0');
15                 j--;
16             }
17             if (carry != 0) {
18                 sum += carry;
19             }
20             int digit = sum % 10;
21             carry = sum / 10;
22             res.insert(0, digit);
23         }
24         return res.toString();
25     }
26 }

 

posted @ 2016-12-02 12:46  neverlandly  阅读(318)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3