首页 > 试题广场 >

整数加法

[编程题]整数加法
  • 热度指数:28749 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
请设计一个算法能够完成两个用字符串存储的整数进行相加操作,对非法的输入则返回 error

数据范围:字符串长度满足

输入描述:
输入为一行,包含两个字符串。


输出描述:
输出为一行。合法情况输出相加结果,非法情况输出error
示例1

输入

123 123
abd 123

输出

246
error
Java做的很累啊。尾部相加,进位保留往前加,加到没有进位为之。
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String a = scanner.next();
        String b = scanner.next();
        if (!legal(a) || !legal(b)) {
            System.out.println("error");
        }else {
            System.out.println(add(a, b));
        }
    }

    public static String add(String a,String b) {
        int i = a.length() - 1;
        int j = b.length() - 1;
        int go = 0;

        String res = "";
        while (i >= 0 && j >= 0) {
            int a1 = Integer.parseInt(a.substring(i, i + 1));
            int b1 = Integer.parseInt(b.substring(j, j + 1));
            int sum = a1 + b1 + go;
            if (sum >= 10) {
                go = 1;
                sum = sum - 10;
            }else {
                go = 0;
            }
            res = sum + res;
            i --;
            j --;
        }

        String rem = i > j ? a.substring(0, i - j) : b.substring(0, j - i);

        if (go == 0) {
            res = rem + res;
        }

        int cur = rem.length() - 1;
        while (cur >= 0) {
            int num = Integer.parseInt(rem.substring(cur, cur + 1));
            int sum = num + go;
            if (sum >= 10) {
                sum = sum - 10;
                go = 1;
            } else {
                go = 0;
                break;
            }
            res = String.valueOf(sum) + res;
            cur --;
        }
        if (go == 1) {
            res = "1" + res;
        }
        return res;
    }
    public static boolean legal(String s) {
        for (int i = 0;i < s.length();i ++) {
            if ('0' <= s.charAt(i) && s.charAt(i) <= '9') {
                continue;
            }else return false;
        }
        return true;
    }
}

发表于 2018-06-14 00:21:26 回复(0)
更多回答
//注意int、long均不能满足需求
import java.util.Scanner;
import java.math.BigInteger;
public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        try{
            BigInteger  n = scanner.nextBigInteger ();
            BigInteger  m = scanner.nextBigInteger ();
            System.out.println(m.add(n));
        }catch(Exception e)
        {
            System.out.println("error");
        }  
    }
}

发表于 2017-08-08 14:13:52 回复(12)

题目要求手撕大整数算法 那些直接调用的也是够了。。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
using namespace std;
//常量区
typedef long long ll;

bool is_num(string a){
    for(int i = 0; i < a.length(); i++)
        if(a[i] > '9' || a[i] < '0') return false;
    return true;
}

//函数区
void MyAdd(string a, string b){
    if(!is_num(a) || !is_num(b)) {printf("error\n"); return; }
    int max_len = max(a.length(), b.length());
    string c = "";
    for(int i = 0; i < max_len; i++) c += '0';
    int al = a.length();
    int bl = b.length();
    if(al < bl)
        for(int i = 0; i < bl - al; i++) a = '0' + a;
    else if(al > bl)
        for(int i= 0; i < al - bl; i++) b = '0' + b;
    for(int i = max_len - 1; i >= 0; i--){
       int tmp = int(a[i]) + int(b[i]) + int(c[i]) - 48*3;
        if(tmp < 10) c[i] = tmp + '0';
        if(tmp >= 10) {
            c[i] = tmp % 10 + '0';
            char ss = (tmp / 10 + '0');
            if(i == 0)  c = ss + c;
            else c[i-1] = ss;
        }
    }
    cout<<c<<endl;
}
//main函数
int main(){
    string a, b;
    while(cin>>a>>b){
        MyAdd(a, b);
    }
    return 0;
}
/*
123 123
abd 123
*/
发表于 2018-09-27 13:08:40 回复(0)
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            String s = scan.nextLine();
            String[] ss = s.split(" ");
            String result = add(ss[0], ss[1]);
            System.out.println(result);
        }
    }
    
    public static String add(String s1, String s2) {
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        if (!checkValid(c1) || !checkValid(c2)) {
            return "error";
        }
        if (c1.length < c2.length) {
            char[] tmp = c1;
            c1 = c2;
            c2 = tmp;
        }
        int cf = 0;
        int i = c1.length - 1, j = c2.length - 1;
        while (j >= 0) {
            int tmp = c1[i] - '0' + c2[j] - '0' + cf;
            cf = tmp / 10;
            c1[i] = (char) (tmp % 10 + '0');
            i--;
            j--;
        }
        while (i >= 0 && cf > 0) {
            int tmp = c1[i] - '0' + cf;
            cf = tmp / 10;
            c1[i] = (char) (tmp % 10 + '0');
            i--;
        }
        StringBuilder sb = new StringBuilder();
        if (cf > 0) {
            sb.append('1');
        }
        for (int k = 0; k < c1.length; k++) {
            sb.append(c1[k]);
        }
        return sb.toString();
    }
    
    public static boolean checkValid(char[] c) {
        for (int i = 0; i < c.length; i++) {
            if (c[i] < '0' || c[i] > '9') {
                return false;
            }
        }
        return true;
    }
}

编辑于 2018-03-22 09:10:13 回复(1)
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
    string stra;
    string strb;
    while(cin >> stra >> strb)
    {
        bool flag = false;
        for(int i = 0; i < stra.size(); i++)
        {
            if(!(stra[i] >= '0' && stra[i] <= '9'))
            {
                cout << "error" << endl;
                flag = true;
                break;
            }
                
        }
        if(flag)
            break;
        for(int i = 0; i < strb.size(); i++)
        {
            if(!(strb[i] >= '0' && strb[i] <= '9'))
            {
                cout << "error" << endl;
                flag = true;
                break;
            }
                
        }
        if(flag)
            break;
        
        string ret;
        int carry = 0;
        int i = stra.size() - 1;
        int j = strb.size() - 1;
        while(i >= 0 && j >= 0)
        {
            int sum = (stra[i] - '0') + (strb[j] - '0') + carry;
            carry = sum / 10;//计算carry和sum不能调换顺序
            sum = sum % 10;
            ret = ret + to_string(sum);
            i--;
            j--;
        }
        while(i >= 0)
        {
            int sum = (stra[i] - '0') + carry;
            carry = sum / 10;
            sum = sum % 10;
            ret = ret + to_string(sum);
            i--;
        }
        while(j >= 0)
        {
            int sum = (strb[j] - '0') + carry;
            carry = sum / 10;
            sum = sum % 10;
            ret = ret + to_string(sum);
            j--;
        }
        if(carry)
            ret = ret + '1';
        reverse(ret.begin(), ret.end());
        cout << ret << endl;
        
    }
}

发表于 2017-10-02 17:02:59 回复(0)
代码巨长。这道题和剑指offer其中一道相似,不过那里面只是将字符串转换为数字。
package 算法题.美团点评;

import java.math.BigInteger;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IntAdd {
	public static void main(String args[]) {
		Scanner input = new Scanner(System.in);
		// 方法一
		// try{
		// BigInteger n = input.nextBigInteger();
		// BigInteger m = input.nextBigInteger();
		// System.out.println(n.add(m));
		// }catch (Exception e) {
		// System.out.println("error");
		// }
	
			String n = input.next();
			String m = input.next();
			String sum = resolute(n, m);
			System.out.println(sum);
		
	}

	public static String resolute(String n, String m) {
		final String ERROR = "error";
		// 判断字符串是否符合标准
		if (n == null || m == null)
			return ERROR;
		if (!isNumber(n) || !isNumber(m)) {
			return ERROR;
		}
		// n、m的正负值
		boolean boolN = isRightNum(n);
		boolean boolM = isRightNum(m);
		if (n.charAt(0) == '+' || n.charAt(0) == '-')
			n = n.substring(1);
		if (m.charAt(0) == '+' || m.charAt(0) == '-')
			m = m.substring(1);
		if (boolN && boolM) { // 同为正值
			return toSum(n, m);
		} else if (!boolN && !boolM) { // 同为负值
			return '-' + toSum(n, m);
		} else {
			// 预处理,n为正数,m为负数,做和。要注意借位。
			if (boolN) {
				return toSub(n, m);
			} else {
				return toSub(m, n);
			}
		}
	}

	/**
	 * 判断一个字符串是否是数字。"-123"、"+123","0123"都是数字
	 * 
	 * @param s
	 *            待判断的字符串
	 * @return
	 */
	public static boolean isNumber(String s) {
		final String REGEX = "[-+\\d]\\d*";
		Pattern pattern = Pattern.compile(REGEX);
		Matcher matcher = pattern.matcher(s);
		if (!matcher.matches())
			return false;
		return true;
	}

	/**
	 * 判断一个字符串是否是正整数
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isRightNum(String s) {
		final String REGEX = "-\\d+";
		Pattern pattern = Pattern.compile(REGEX);
		Matcher matcher = pattern.matcher(s);
		if (matcher.matches())
			return false;
		return true;
	}

	/**
	 * 消除前导0, 0000123输出 123
	 * 
	 * @param s
	 * @return
	 */
	public static String ignore0(String s) {
		int i;
		for (i = 0; i < s.length(); i++) {
			if (s.charAt(i) != '0')
				break;
		}
		return s.substring(i);
	}

	/**
	 * 两个正数相加
	 * 
	 * @param n
	 * @param m
	 * @return
	 */
	public static String toSum(String n, String m) {

		// System.out.println("调用了tosum():"+n+" "+m);

		StringBuffer str = new StringBuffer();
		int tem = 0; // 存储进位
		int i = n.length() - 1, j = m.length() - 1;
		// 两个正数相加、或两个负数相加
		for (; j >= 0 && i >= 0; i--, j--) {
			tem = tem + n.charAt(i) - '0' + m.charAt(j) - '0';
			str.append(tem % 10);
			tem /= 10;

		} // 处理多出来的位
		while (i >= 0) {
			tem = tem + n.charAt(i) - '0';
			str.append(tem % 10);
			tem /= 10;
			i--;
		}
		while (j >= 0) {
			tem = tem + m.charAt(j) - '0';
			str.append(tem % 10);
			tem /= 10;
			j--;
		}
		str.append(tem);
		str = str.reverse();
		return ignore0(str.toString());
	}

	/**
	 * 字符串做差 n-m 预处理
	 * 
	 * @param n
	 * @param m
	 * @return
	 */
	public static String toSub(String n, String m) {

		if (n.length() > m.length()) {
			return doSub(n, m);
		} else if (n.length() < m.length()) {
			return '-' + doSub(m, n);
		} else {
			if (n.compareTo(m) >= 0) {
				return doSub(n, m);
			} else {
				return '-' + doSub(m, n);
			}
		}
	}

	/**
	 * 做差n-m
	 * 
	 * @param n
	 * @param m
	 * @return
	 */
	public static String doSub(String n, String m) {
		StringBuffer str = new StringBuffer();
		int tem = 0;
		int i = n.length() - 1, j = m.length() - 1;
		for (; i >= 0 && j >= 0; i--, j--) {
			tem = n.charAt(i) - tem - m.charAt(j);
			if (tem<0) {
				tem = tem + 10; 
				str.append(tem);
				tem = 1;
			} else {
				str.append(tem);
				tem = 0;
			}
		}
		while (i >= 0) {
			tem = n.charAt(i) - '0' - tem;
			if (tem < 0) {
				str.append(tem + 10);
				tem = 1;
			} else {
				str.append(tem);
				tem = 0;
			}
			i--;
		}
		str = str.reverse();
		String s = ignore0(str.toString());
		if(s == null || s.isEmpty()) s = "0";
		return s;
	}
}


发表于 2018-04-16 17:22:37 回复(0)
//本题如 @是个Offer就行 同学说的一样,int long都不能满足。
//思路:借助栈,先进后出的原则,从低位开始相加,依次存到栈中
//特别注意相加的进位flag,初始为0
//经 @Striver_zhoudw 同学和 @至心 同学 的提醒,已对长度不一致的情况做了修改,再次感谢  #include <iostream>
#include <string>
#include <stack>
using namespace std;
int isalldi(string str)
{
for (int i = 0; i < str.size(); i++)
{
    if (!isdigit(str[i])) //判断是否有非数字的元素
    {
        cout<<"error"<<endl;
        return 0;
    }
}
    return 1;
}
int main()
{
    string str1,str2;
    while(cin>>str1>>str2)
    {
        int sum=0;
        stack<int>si;
        int flag=0;
        if(isalldi(str1)&&isalldi(str2))//str1 str2 都是数字
        {
            if (str1.size()<str2.size()) //保证str1是较长的字符串
            {
                swap(str1,str2);
            }              
            while (m>=0) //较短的字符串长度来控制加法的次数             
            {
                sum=(str1[n--]-'0')+(str2[m--]-'0')+flag;
                flag=sum/10;
                si.push(sum%10);
            }
            int n=str1.size()-1;
            int m=str2.size()-1;
            int len=n-m; //两个字符串的长度差
            while (len-->0) //如果长度不一致,需要把较长的字符串再与进位相加           
            {
                sum=flag+(str1[len]-'0');
                flag=sum/10;
                si.push(sum%10);
            }
            if (flag)//注意如果加完之后进位=1,仍需要再入栈的
            {
                si.push(flag);
            }
            while(!si.empty())//栈非空
            {
                cout<<si.top();//弹出顶层元素
                si.pop();
            }
            cout<<endl;
        }
    }
    return 0;
}

编辑于 2017-12-27 11:14:17 回复(5)
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str1 = in.next();
            String str2 = in.next();
            System.out.println(caculate(str1,str2));
        }
    }
    public static String caculate(String s1,String s2){
        int i = s1.length() - 1,j = s2.length() - 1;
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        while(i >= 0 || j >= 0 || carry != 0){
            if(i >= 0 && !Character.isDigit(s1.charAt(i)) || j >= 0 && !Character.isDigit(s2.charAt(j))) return "error";
            int m = i < 0 ? 0 : s1.charAt(i) - '0';
            int n = j < 0 ? 0 : s2.charAt(j) - '0';
            int sum = m + n + carry;
            sb.append(sum % 10);
            carry = sum / 10;
            i --;
            j --;
        }
        return sb.reverse().toString();
    }
}

发表于 2021-08-13 15:13:27 回复(0)
1.正儿八经法:模拟加法的竖式,遇到ascii码的取值不在[48,57]范围内就直接打印error
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] strNum = br.readLine().trim().split(" ");
        System.out.println(add(strNum[0].toCharArray(), strNum[1].toCharArray()));
    }
    
    private static String add(char[] num1, char[] num2) {
        StringBuilder sb = new StringBuilder();
        int len1 = num1.length, len2 = num2.length;
        if(len1 < len2){
            char[] temp = num1;
            num1 = num2;
            num2 = temp;
        }
        int carry = 0;
        int i = num1.length - 1, j = num2.length - 1;
        while(i >= 0 && j >= 0){
            if(num1[i] > 57 || num1[i] < 48 || num2[j] > 57 || num2[j] < 48)
                return "error";
            int num = (num1[i] - '0') + (num2[j] - '0') + carry;
            carry = num / 10;
            sb.append(num % 10);
            i --;
            j --;
        }
        while(i >= 0){
            if(num1[i] > 57 || num1[i] < 48)
                return "error";
            int num = (num1[i] - '0') + carry;
            carry = num / 10;
            sb.append(num % 10);
            i --;
        }
        if(carry > 0) sb.append(carry);
        return sb.reverse().toString();
    }
}
2.偷懒法:直接转成数字相加,遇到异常就打印error
try:
    num1, num2 = map(int, input().split())
    print(num1 + num2)
except:
    print("error")



编辑于 2021-02-02 13:26:33 回复(0)
用栈、链表、队列,都可以实现,不难理解
有一个小技巧是先让两个容器对齐,这样就不用处理特殊情况了,记得处理进位就可以了
import java.util.Scanner;
import java.util.Stack;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str1=sc.next();
        String str2=sc.next();
        int len1=str1.length();
        int len2=str2.length();
        String result="";
        
        Stack<Integer> stack1=new Stack<>();
        Stack<Integer> stack2=new Stack<>();
        Stack<Integer> stack3=new Stack<>();
        //让两个栈对齐
        if(len1>len2)
        {
            int count=len1-len2;
            while(count-->0)
                stack2.push(0);
        }
        else if(len1<len2)
        {
            int count=len2-len1;
            while(count-->0)
                stack1.push(0);
        }
        
        //分别入栈
        for(int i=0;i<str1.length();i++)
        {
            char ch=str1.charAt(i);
            if(ch<'0'||ch>'9')
            {
                System.out.println("error");
                return;
            }
            stack1.push(ch-'0');
        }
        for(int i=0;i<str2.length();i++)
        {
            char ch=str2.charAt(i);
            if(ch<'0'||ch>'9')
            {
                System.out.println("error");
                return;
            }
            stack2.push(ch-'0');
        }
        
        //相加入新栈
        int num1,num2,num3,add=0;
        while( !stack1.isEmpty() && !stack2.isEmpty() )
        {
            num1=stack1.pop();
            num2=stack2.pop();
            num3=num1+num2+add;
            add=num3/10;
            num3%=10;
            stack3.push(num3);
        }
        
        //处理最后的进位
        if(add==1)
            stack3.push(1);
       
        while(!stack3.isEmpty())
            result+=stack3.pop();
        
        System.out.println(result);
    }
}




发表于 2019-09-11 01:07:59 回复(0)
/*
 总体思路就是把两个字符串倒序的分别放到两个整型数组中,
 然后从第一位开始进行对应相加,大于10的进一位,最后输出的时候倒序输出就行
  细节描述在代码注释中
*/
import java.util.*;
public class Main{
    public static void main(String []args){
        Scanner sc = new Scanner(System.in);
          while(sc.hasNext()){
              String str = sc.nextLine();
              String []strs=str.split(" ");
             
             //把最长的那个字符串放在第一位
              if(strs[0].length()<strs[1].length()){
                  String temp = strs[0];
                  strs[0] = strs[1];
                  strs[1] = temp;
              }
              
              int j =0;
              int k =0;
              int []num1 = new int[strs[0].length()+1];
              int []num2 = new int[strs[1].length()];

             //在判断字符串是否非法时,顺便给整型数组赋值
              for(int i =strs[0].length()-1;i>=0;i--){
                  if(strs[0].charAt(i)<='0'|| strs[0].charAt(i)>='9'){
                      System.out.println("error");
                      System.exit(0);
                  }
                  num1[j++] = Integer.parseInt(String.valueOf(strs[0].charAt(i)));
              }
            //在判断字符串是否非法时,顺便给整型数组赋值
              for(int i =strs[1].length()-1;i>=0;i--){
                  if(strs[1].charAt(i)<='0'|| strs[1].charAt(i)>='9'){
                      System.out.println("error");
                      System.exit(0);
                  }
                  num2[k++] = Integer.parseInt(String.valueOf(strs[1].charAt(i)));
              }


              int flag = 0;//标志位,如果进位就为1,否则为0
              int i =0;
              for(;i<num2.length;i++){
                  if(num1[i] + num2[i] >=10){
                      num1[i] = (num1[i]+num2[i])-10+flag;
                      flag = 1;
                  }else{
                      num1[i] = num1[i]+num2[i]+flag;
                      flag =0;
                  }
              }
             //这里很重要,因为有可能num2最后一位加完之后又进了一位
              num1[i] +=flag;

              String res="";
              boolean f = true;
              for(int m =num1.length-1;m>=0;m--){
                  //这一步是去掉最前面为0 的可能
                  if(num1[m] == 0 && f ==true)
                      continue;
                  res +=num1[m];
              }
              System.out.println(res);
          }
    }
}

发表于 2019-03-11 21:25:46 回复(0)
#include <iostream>
#include <string>
using namespace std;

bool isNum(string str)
{
    for(int i = 0; i < str.size(); i++)
        if(str[i] <= '0' || str[i] >= '9')
            return false;
    return true;
}

void pinjie(string str1, string str2)
{
    int i1 = str1.size() - 1;
    int i2 = str2.size() - 1;
    string str = "";
    int c = 0;//进位位
    
    while(1)
    {
        int n;
        if(i1 >= 0 && i2 >= 0)
            n = str1[i1] + str2[i2] - '0' - '0' + c;
        else if(i1 >= 0 && i2 < 0)
            n = str1[i1] - '0' + c;
        else if(i2 >= 0 && i1 < 0)
            n = str2[i2] - '0' + c;
        else
            break;
        
        if(n > 10)
        {
            c = 1;
            n %= 10;
        }
        else
            c = 0;
        
        str = (char)(n + '0') + str;
        i1--;
        i2--;
    }
    
    if(c)str = "1" + str;
    cout << str << endl;
}

int main()
{
    string str1,str2;
    cin >> str1 >> str2;
    
    if(isNum(str1) && isNum(str2))
        pinjie(str1, str2);
    else
        cout << "error" << endl;
    
    return 0;
}

编辑于 2018-07-27 21:28:14 回复(0)
<?php
//大数相加
function bigAdd($s1,$s2){
    $len1 = strlen($s1);
    $len2 = strlen($s2);
    $j = 0;//进位标识符
    $re = '';
    for($inx1 = $len1-1,$inx2 = $len2-1;($inx1>=0||$inx2>=0);--$inx1,--$inx2){
        $item1 = ($inx1>=0) ? (int)$s1[$inx1]:0;
        $item2 = ($inx2>=0) ? (int)$s2[$inx2]:0;
        $sum = $item1 + $item2 + $j;
        if($sum>9){
            $j=1;
            $sum-=10;
        }else $j=0;
        $re = (string)$sum.$re;
    }
    if($j>0) $re = (string)$j.$re;
    return $re;
}
$arr = explode(" ",trim(fgets(STDIN)));
$s1 = $arr[0];
$s2 = $arr[1];
if(!is_numeric($s1)||!is_numeric($s2)) echo 'error';
else echo bigAdd($s1,$s2);

发表于 2018-07-23 22:36:18 回复(0)
WAK头像 WAK
#include<iostream>
#include<string>
using namespace std;
int main(){
    string str1,str2;
    while(cin>>str1>>str2){
        int s1 = str1.size();
        int s2 = str2.size();
        string max = (s1>s2)?str1:str2;  //将长短字符串区分出来
        string min = (s1>s2)?str2:str1;
        int diff = (s1>s2)?s1-s2:s2-s1;
        string res = "0";
        for(int i = 0;i<diff;i++){            //短字符串前面补0,使长度移植
            min = res+min;
        }
        int *** = 0;
        string re = "";
        int c = 0;
        for(int i = max.size()-1;i>=0;i--){   //从个位往前进行进位的加法运算,结果存到字符串中
            if(min[i]<'0'||min[i]>'9'||max[i]<'0'||max[i]>'9'){
                *** = 1;
                break;
            }
            else{
                int a = min[i]-'0'+max[i]-'0'+c;
                if(a>9){
                    c = 1;
                    a = a-10;
                }
                char p = '0'+a;
                re += p;
            }
        }
        if(*** == 1)    //根据***的值,判断输出error还是结果字符串(倒序输出),若进位为1,还要     
            cout<<"error"<<endl;                                            //先输出进位
        else{
            if(c)
                cout<<c;
            for(int i = re.size()-1;i>=0;i--)
                cout<<re[i];
            cout<<endl;
        }
    }
    return 0;
}
发表于 2018-06-27 22:40:11 回复(0)
//直接写大数类,先反向,然后ab补齐,运算,再反向,over
#include<iostream>
#include<algorithm>
using namespace std;
class BigNumber{
    string s;
public:
    BigNumber(string s){
        for(int i=0;i<s.size();++i)
        {
            if(s[i]<'0'||s[i]>'9')
                throw "Error";
            this->s=s;
        }
    }
    BigNumber operator + (BigNumber other)
    {
        string a=other.s;
        string b=s;
        reverse(a.begin(),a.end());
        reverse(b.begin(),b.end());
        int mx=max(a.size(),b.size());
        while(a.size()<mx)
            a+='0';
        while(b.size()<mx)
            b+='0';
        BigNumber ans("");
        while(ans.s.size()<=mx)
            ans.s+='0';
        for(int i=0;i<mx;++i)
        {
            ans.s[i]+=a[i]-'0';
            ans.s[i]+=b[i]-'0';
            if(ans.s[i]>'9')
            {
                ans.s[i]-=10;
                ans.s[i+1]++;
            }
        }
        if(ans.s[mx]=='0')
            ans.s.erase(ans.s.end()-1);
        reverse(ans.s.begin(),ans.s.end());
        return ans;
    }
    friend ostream& operator <<(ostream& o,const BigNumber& n)
    {
        o<<n.s;
        return o;
    }
};
int main()
{
    string a,b;
    while(cin>>a>>b)
    {
        try{
            BigNumber A(a);
            BigNumber B(b);
            cout<<(A+B)<<endl;
        }catch(...)
        {
            cout<<"error"<<endl;
        }
    }
    return 0;
}

发表于 2018-05-23 14:52:36 回复(0)
#include<iostream>
#include<string>
using namespace std;

bool is_number(string s)
{
    for (int i = 0; i < s.length(); i++)
    {
        if (s[i] < '0' || s[i] > '9') return false;
    }
    return true;
}

int main()
{
    string s1, s2;
    while (cin >> s1 >> s2)
    {
        int i, carry, flag = 0, digit = s1.length() > s2.length() ? s1.length() : s2.length();
        string ex1, ex2, num1, num2;
        int *sum = new int[digit + 1]{ 0 };

        for (i = 0; i < digit - s1.length(); i++) ex1 += "0";
        for (i = 0; i < digit - s2.length(); i++) ex2 += "0";

        num1 = ex1 + s1;
        num2 = ex2 + s2;
        if (is_number(num1) && is_number(num2))
        {
            flag = 1;
            for (i = digit - 1; i >= 0; i--)
            {
                sum[i + 1] = (num1[i] - '0') + (num2[i] - '0');
            }
        }
        for (i = digit ; i > 0; i--)
        {
            if (sum[i] >= 10)
            {
                carry = sum[i] / 10;
                sum[i] %= 10;
                sum[i - 1] += carry;
            }
        }
        if (flag == 0) cout << "error";
        else
        {
            if (sum[0] == 0) for (i = 1; i <= digit; i++) cout << sum[i];
            else for (i = 0; i <= digit; i++) cout << sum[i];
        }
        cout << endl;
    }
    system("pause");
    return 0;
}
发表于 2018-04-09 19:57:16 回复(1)
#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using namespace std;

bool is_legal(string str)
{
    for (int i = 0; i < str.length(); ++i)
    {
        if (!isdigit(str[i]))
        {
            return false;
        }
    }
    
    return true;
}

string add_string(string str1, string str2)
{
    string res = "";
    int flag = 0, value = 0, sum = 0;
    vector<int> res_tmp;

    if (str1.size()<str2.size())        // 保证str1的长度最长
    {
        swap(str1, str2); 
    } 
    
    for (int i = str2.size() - 1; i >= 0; --i)    // 相同位 从低位开始相加
    {
        sum = (str1[i] - '0') + (str2[i] - '0') + flag;
        value = sum % 10;
        flag  = sum / 10;
        
        res_tmp.push_back(value);
    }
    
    for (int i = str2.size(); i < str1.size(); ++i)    // 将str1多余的位数和进位相加
    {
        sum = (str1[i] - '0') + flag;
        value = sum % 10;
        flag  = sum / 10;
        
        res_tmp.push_back(value);
    }
    
    if (flag == 1)
    {
        res_tmp.push_back(flag);
    }
    
    for (int i = res_tmp.size() - 1; i >= 0; --i)
    {
        string tmp = to_string(res_tmp[i]);
        res += tmp;
    }
        
    return res;
}

int main()
{
    string str_input;
    while (getline(cin, str_input))
    {
        if (!str_input.empty())
        {
            string str_tmp1 = "";
            string str_tmp2 = "";
            
            int position = str_input.find(' ');
            str_tmp1 = str_input.substr(0, position);
            str_tmp2 = str_input.substr(position + 1, str_input.length() - position);
            
            if (is_legal(str_tmp1) && is_legal(str_tmp2))
            {
                cout << add_string(str_tmp1, str_tmp2) << endl;
            }
            else
            {
                cout << "error" << endl;
            }
        }
    }
    
    return 0;
} 
编辑于 2018-03-20 16:25:25 回复(0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#define N 110
int main()
{

    char a[N],b[N],e;
    int la[N]={0},lb[N]={0},c[N]={0},k=0,flag1=0,flag2=0;
    int lena,lenb,max,i=0,j=0;
    e=getchar();
    while(e!=' ')
    {
        if(e>'9'||e<'0'){
            flag1=1;break;
        }
        a[i]=e;
        i++;
        e=getchar();
    }
    a[i]='\0';
    e=getchar();
    while(e!='\n')
    {

        if(e>'9'||e<'0'){
            flag2=1;break;
        }
        b[j]=e;
        j++;
        e=getchar();
    }
    b[j]='\0';
    lena=strlen(a);
    lenb=strlen(b);
    for(i=lena-1;i>=0;i--)
        {
            if(a[i]>'9'||a[i]<'0')
            {flag1=1;break;}
            la[i]=a[lena-i-1]-'0';
    }
    for(i=lenb-1;i>=0;i--)
    {
        if(b[i]>'9'||b[i]<'0')
            {flag2=1;break;}
        lb[i]=b[lenb-i-1]-'0';
    }
    if(flag1==1||flag2==1)
        printf("error\n");
    else
    {
        if(lena>lenb)max=lena;
    else max=lenb;
    for(i=0;i<=max;i++)
    {
        c[i]=(la[i]+lb[i]+k)%10;
        k=(la[i]+lb[i]+k)/10;
    }
    if(c[max]>0)printf("%d",c[max]);
    for(i=max-1;i>=0;i--)printf("%d",c[i]);
    printf("\n");
    }

    return 0;
}

发表于 2018-03-14 15:03:24 回复(0)
来一个比较短的C/C++版本的AC代码,因为这个题没有考虑正负号,所以可以进行简化,因为长度最多100位所以int或long都会溢出,利用string模拟手算即可,c为进位符。
#include <iostream>
#include <string>

using namespace std;

string add(string a, string b) {
    int i = a.size(), j = b.size();
    int c = 0;
    string ans = "";
    while (i || j || c) {
        if ((i > 0 && !isdigit(a[i - 1])) || (j > 0 && !isdigit(b[j - 1]))) return "error";
        int x = i > 0 ? a[--i] - '0' : 0;
        int y = j > 0 ? b[--j] - '0' : 0;
        int tmp = x + y + c;
        if (tmp >= 10) {
            tmp %= 10;
            c = 1;
        } else c = 0;
        ans = to_string(tmp) + ans;
    }
    return ans;
}

int main() {
    string strA, strB;
    while (cin>>strA>>strB) cout<<add(strA, strB)<<endl;
    return 0;
}

发表于 2018-01-25 15:29:37 回复(1)
//C++实现,代码比较长
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
    int i,j,flag=0;
    char a[105]={0},b[105]={0};
    int c[105]={0};
    while (scanf("%s %s",&a,&b)>0)
    {
        for (i=0;i<strlen(a);i++)
        {
            if (!(isdigit(a[i])))
            {
                printf("error\n");
                goto a;
            }
        }
        for (i=0;i<strlen(b);i++)
        {
            if (!(isdigit(b[i])))
            {
                printf("error\n");
                goto a;
            }
        }
        if (strlen(a)<strlen(b))
        {
            for (i=0;i<strlen(b)-strlen(a);i++)
            c[i]=0;
            for (j=0;j<strlen(a);i++,j++)
            c[i]=a[j]-'0';
            for (i=strlen(b)-1;i>=0;i--)
            {
                c[i]=c[i]+b[i]-'0'+flag;
                flag=0;
                if (c[i]>9)
                {
                    flag=1;
                    c[i]-=10;
                }
            }
            if (flag==1)
            printf("1");
            for (i=0;i<strlen(b);i++)
            printf("%d",c[i]);
        }
        else
        {
            for (i=0;i<strlen(a)-strlen(b);i++)
            c[i]=0;
            for (j=0;j<strlen(b);i++,j++)
            c[i]=b[j]-'0';
            for (i=strlen(a)-1;i>=0;i--)
            {
                c[i]=c[i]+a[i]-'0'+flag;
                flag=0;
                if (c[i]>9)
                {
                    flag=1;
                    c[i]-=10;
                }
            }
            if (flag==1)
            printf("1");
            for (i=0;i<strlen(a);i++)
            printf("%d",c[i]);
        }
        printf("\n");
        a:;
    }
}
发表于 2018-01-22 23:03:07 回复(1)

问题信息

难度:
191条回答 16644浏览

热门推荐

通过挑战的用户

查看代码