zoukankan      html  css  js  c++  java
  • LeetCode——Add Strings

    LeetCode——Add Strings

    Question

    Given two non-negative integers 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.

    解题思路

    这道题就是所谓的大整数加法操作,因为超过了计算机所能表示的范围数,所以用字符串表示,然后注意到就是,当两个长度不一样的时候,可以考虑往一个较短的字符串补‘0’,让两个字符串的长度保持一致。

    具体实现

    class Solution {
    public:
        // 大整数加法
        string addStrings(string num1, string num2) {
            string n1(num1.rbegin(), num1.rend());
            string n2(num2.rbegin(), num2.rend());
    
            int size1 = n1.length();
            int size2 = n2.length();
            if (size1 < size2) {
                for (int i = 0; i < size2 - size1; i++) {
                    n1 += '0';
                }
            }
            if (size1 > size2) {
                for (int j = 0; j < size1 - size2; j++) {
                    n2 += '0';
                }
            }
    
            int remainer = 0;
            string str;
            for (int i = 0; i < n1.length(); i++) {
                int sum = n1[i] - 48 + n2[i] - 48 + remainer;
                remainer = 0;
                if (sum >= 10) {
                    sum = sum - 10;
                    remainer = 1;
                }
                char tmp = sum + 48;
                str += tmp;
            }
            if (remainer == 1)
                str += '1';
    
            string str1(str.rbegin(), str.rend());
            return str1;
        }
    };
    
  • 相关阅读:
    [洛谷P2711]小行星
    [洛谷P2264]情书
    [洛谷P2626]斐波那契数列(升级版)
    [洛谷P3195][HNOI2008]玩具装箱TOY
    [洛谷P3254]圆桌问题
    [洛谷P1251]餐巾计划问题
    [洛谷P4015]运输问题
    [洛谷P2604][ZJOI2010]网络扩容
    [洛谷P4001][BJOI2006]狼抓兔子
    [洛谷P3153] [CQOI2009]跳舞
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/6656494.html
Copyright © 2011-2022 走看看