zoukankan      html  css  js  c++  java
  • 415. 字符串相加

    415. 字符串相加

    难度简单

    给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

    提示:

    1. num1 和num2 的长度都小于 5100
    2. num1 和num2 都只包含数字 0-9
    3. num1 和num2 都不包含任何前导零
    4. 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式

    法一+法二:字符转字符串越界了。以前ans += ""+ch;就行的呀。

    class Solution {
    public:
        string addStrings(string num1, string num2) {
            string ans = "";
            int n1 = num1.length(), n2 = num2.length();
            int diff = abs(n1-n2);
            if(n1 < n2){
                for(int i=0; i<diff; i++){
                    num1 = "0" + num1;
                }
            }
            else{
                for(int i=0; i<diff; i++){
                    num2 = "0" + num2;
                }
            }
            int extra = 0, tmp;
            //cout << num1 << ' ' << num2 << endl;
            for(int i=num1.length()-1; i>=0; i--){
                int sum = (num1[i]-'0') + (num2[i]-'0')+extra;
                tmp = sum%10;
                extra = sum/10;
                cout << tmp << ' ' << extra << endl;
                char ch = tmp+'0';
                cout << ch << endl;
                //ans += ""+(char)(tmp+'0'); RuntimeError
                ///ans.append(1, ch);
                ////string temp = "";
                ////temp.append(1, ch);
                ////ans = temp+ ans;
            ans = ch+ans; //这样真的行。 }
    ///reverse(ans.begin(), ans.end()); if(extra){ ans = "1"+ans; } return ans; } };

    时间:O(n)

    空间:O(n)

     自己实现的官解:

    class Solution {
    public:
        string addStrings(string num1, string num2) {
            int i = num1.length()-1, j = num2.length()-1, extra = 0;
            string ans = "";
            while(i>=0 || j>=0 || extra){
                int x = i>=0 ? num1[i]-'0':0;
                int y = j>=0 ? num2[j]-'0':0;
                int res = x+y+extra;
                char ch = '0'+(res%10);
                ans = ch+ans;
                extra = res/10;
                i--;
                j--;
            }
            return ans;
        }
    };
  • 相关阅读:
    Equivalent Sets HDU
    Chemical table CFR500 div2D(并查集)
    How do I create an installation log?
    Error 1937.An error occurred during the installation of assembly...
    InstallShield 版本转换
    Convert CString to TCHAR
    InstallShield : 如何查找编译后的 Merge Module存放路径
    Msi.h causes compilation error in vs2010
    区间调度(贪心)
    硬币问题(贪心)
  • 原文地址:https://www.cnblogs.com/AbsolutelyPerfect/p/14941075.html
Copyright © 2011-2022 走看看