zoukankan      html  css  js  c++  java
  • [LeetCode] Add Strings

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

    Note:

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

    给定两个只含有数字字符串,将字符串中的数字和返回一个字符串。并且要求不能使用整数类库及将输入直接转换成整数。这需要对两个字符串中数字对位相加并处理相加所得的进位。每完成一位的数相加,把它放去结果字符串中。最后将所得的结果字符串数组反转即可。

    class Solution {
    public:
        string addStrings(string num1, string num2) {
            string s;
            int carry = 0;
            int i = num1.size() - 1;
            int j = num2.size() - 1;
            while (i >= 0 || j >= 0 || carry) {
                int sum = 0;
                if (i >= 0) {
                    sum = sum + num1[i] - '0';
                    i--;
                }
                if (j >= 0) {
                    sum = sum + num2[j] - '0';
                    j--;
                }
                sum = sum + carry;
                carry = sum / 10;
                sum = sum % 10;
                s = s + to_string(sum);
            }
            reverse(s.begin(), s.end());
            return s;
        }
    };
    // 16 ms
  • 相关阅读:
    多线程(一) NSThread
    Swift 烧脑体操(一)
    Swift 烧脑体操(二)
    UINavigationController使用的注意事项
    更多请查看我的文章
    本地通知
    网络编程(二)NSURLSessionConfiguration
    A
    51Nod 1116 K进制下的大数(暴力枚举)
    51Nod 1065 最小正子段和
  • 原文地址:https://www.cnblogs.com/immjc/p/7206747.html
Copyright © 2011-2022 走看看