首页 > 试题广场 >

大数加法

[编程题]大数加法
  • 热度指数:3326 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
以字符串的形式读入两个数字,再以字符串的形式输出两个数字的和。

输入描述:
输入两行,表示两个数字a和b,-109 <= a , b <= 10,用双引号括起。


输出描述:
输出a+b的值,用双引号括起。
示例1

输入

"-26"
"100"

输出

"74"
#include <stdio.h>
int main(){
    long a;
    long b;
    char c;
    scanf("\"%d\"",&a);
    c=getchar();
    scanf("\"%d\"",&b);
    printf("\"%d\"",a+b);
    return 0;
}
就正常的加法不就行了吗??没看到其他大佬怎么程序那么复杂,输入限制下条件呀。
发表于 2020-04-09 11:50:57 回复(3)
#include<iostream>
(720)#include<string>
#include<vector>
 
using namespace std;

// 两个字符串相加,模拟手算。两个字符串只有数字,没有符号
string addString(string str1,string str2){
    string res="";
    int pos1=str1.size()-1, pos2=str2.size()-1;
    int C=0, num1=0, num2=0, sum=0;
    // 从后向前逐个相加。
    for(;pos1>=0||pos2>=0; pos1--, pos2--){
        num1=pos1>=0? str1[pos1]-'0': 0;
        num2=pos2>=0? str2[pos2]-'0': 0;
        sum=num1+num2+C;
        res= to_string(sum%10) + res;
        C=sum/10;
    }
    if(C){
        res= to_string(C)+res;
    }
    return res;
}
// 两个字符串相减,模拟手算。两个字符串只有数字,没有符号
string minusString(string str1, string str2){
    bool res_positive=true;
    // 若str1表示的数字小于str2的,两者交换,并将结果符号设为负。
    if(str1.size()<str2.size() || (str1.size()==str2.size()&& str1<str2)){
        res_positive=false;
        string temp=str2;
        str2=str1;
        str1=temp;
    }
    string res="";
    int pos1=str1.size()-1, pos2=str2.size()-1;
    int C=0, num1=0, num2=0;
    // 从后向前逐个相减
    for(;pos1>=0||pos2>=0; pos1--, pos2--){
        num1=pos1>=0? str1[pos1]-'0': 0;
        num2=pos2>=0? str2[pos2]-'0': 0;
        if(num1-C<num2){
            num1= num1-C+10;
            C=1;
        }else{
            num1=num1-C;
            C=0;
        }
        res= to_string(num1-num2) + res;
    }
    pos1=0;
    // 找到第一个非零位置
    while(pos1<res.size()&& res[pos1]=='0'){
        pos1++;
    }
    if(pos1==res.size()){ // res都是0
        res="0";
    }else if(pos1>0){  // res前缀部分是0
        res=res.substr(pos1);
    }
    if(res_positive==false){ // 结果res是负数
        res= "-"+res;
    }
    return res;
}
 
int main(){
    string str1, str2;
    getline(cin, str1);
    getline(cin, str2);
    // 去掉引号
    str1=str1.substr(1, str1.size()-2);
    str2=str2.substr(1, str2.size()-2);
    // 去掉正负号,记录数值正负
    bool positive1=true, positive2=true;
    if(str1[0]=='-'){
        positive1=false;
        str1=str1.substr(1);
    }else if(str1[0]=='+')
        str1=str1.substr(1);
    if(str2[0]=='-'){
        positive2=false;
        str2=str2.substr(1);
    }else if(str2[0]=='+')
        str2=str2.substr(1);
     
    string res;
    // 这两个字符串异号
    if(positive1 ^ positive2){
        if(positive1==false){ // 第一个字符串是负数
            res=minusString(str2, str1);
        }else { // 第二个字符串是负数
            res=minusString(str1,str2);
        }
    }else{ // 同号
        res=addString(str1,str2);
        if(positive1==false)
            res="-"+res;
    }
    cout<<"\"" <<res<<"\""<<endl;
     
    return 0;
}

发表于 2020-03-22 21:48:08 回复(2)
import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("\""+(Integer.valueOf(in.nextLine().replace("\"",""))+Integer.valueOf(in.nextLine().replace("\"","")))+"\"");
    }
}

发表于 2020-03-12 17:31:08 回复(1)
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string a,b;
    cin>>a;
    cin>>b;
    a=a.substr(1,a.size()-2);
    b=b.substr(1,b.size()-2);
    int r1=stoi(a,0,10);
    int r2=stoi(b,0,10);
    int r=r1+r2;
    cout<<'"'<<r<<'"'<<endl;
    return 0;
}
发表于 2020-08-12 18:41:42 回复(0)
//使用c++的stringstream类实现类型转换
#include<iostream>
#include<sstream>
using namespace std;

int main() {
    string str1, str2, str3;
    cin >> str1;  //以string类型输入
    cin >> str2;
    //使用stringstream类,因为它方便类型转换
    stringstream ss1(str1); //将输入的字符串内容传到stringstream类对象中
    stringstream ss2(str2);

    int a, b;
    ss1.ignore(1, '"'); //忽略第一个冒号
    ss2.ignore(1, '"');  
    ss1 >> a;  //将stringstream中内容流出到int型变量中
    ss2 >> b;

    stringstream ss3;
    ss3 <<'"'<< a + b<<'"';  //用stringstream的灵活性组建输出的格式
    str3 = ss3.str();
    cout << str3;  //结果以string形式输出

    return 0;
}
发表于 2020-05-25 17:07:39 回复(0)
package main

import (
	"fmt"
	"strconv"
)
    
func main() {
	var numOne,numTwo string
	fmt.Scanln(&numOne)
	fmt.Scanln(&numTwo)
	n, _ := strconv.ParseInt(numOne[1:len(numOne)-1], 10, 64)
	m, _ := strconv.ParseInt(numTwo[1:len(numOne)-1], 10, 64)
	fmt.Println("\"" + fmt.Sprintf("%d", m+n) + "\"")
}
golang的,大数写法不知道为啥没通过,然后直接int就行
发表于 2020-03-24 23:59:31 回复(0)
//题目给出的范围不足以让两个int相加越界
import java.util.Scanner;
 
/**
 * @ClassName Main
 * @Description TODO
 * @Author Wlison
 * @Date 2020/3/11 9:38
 * @Version 1.0
 **/
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String a = sc.nextLine();
            String b = sc.nextLine();
            String res ="\""+ (Integer.parseInt(a.substring(1,a.length()-1))+Integer.parseInt(b.substring(1,b.length()-1)))+"\"";
            System.out.println(res);
        }
    }
}

发表于 2020-03-12 09:48:23 回复(0)
import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str1 = scanner.nextLine();
        String str2 = scanner.nextLine();
        //去除引号
        str1 = str1.substring(1,str1.length()-1);
        str2 = str2.substring(1,str2.length()-1);

        //符号位
        char str1D = str1.charAt(0);
        char str2D = str2.charAt(0);
        if (str1D!='-')str1D = '+';
        if (str2D!='-')str2D = '+';

        //位数
        int str1L = str1.charAt(0)=='-'?str1.length()-1:str1.length();
        int str2L = str2.charAt(0)=='-'?str2.length()-1:str2.length();
        str1 = str1.charAt(0)=='-'?str1.substring(1,str1.length()):str1;
        str2 = str2.charAt(0)=='-'?str2.substring(1,str2.length()):str2;

        StringBuffer result = new StringBuffer();


        //判断符号情况
        if (str1D=='-'&&str2D=='-'){
            int up = 0;
            int i=str1L,j=str2L;
            for (i=str1L-1,j=str2L-1;i>=0&&j>=0;i--,j--){
                int temp = Integer.parseInt(String.valueOf(str1.charAt(i)))+Integer.parseInt(String.valueOf(str2.charAt(j)))+up;
                up = temp/10;
                result.append(temp%10);
            }
            //System.out.println("\""+result.reverse().toString()+"\"");
            while (i>=0){
                int temp = Integer.parseInt(String.valueOf(str1.charAt(i)))+up;
                up = temp/10;
                result.append(temp%10);
                i--;
            }
            while (j>=0){
                int temp = Integer.parseInt(String.valueOf(str2.charAt(j)))+up;
                up = temp/10;
                result.append(temp%10);
                j--;
            }
            if (up != 0)result.append(up);
            result.append('-');
            System.out.println("\""+result.reverse().toString()+"\"");
        }else if ((str1D=='+'&&str2D=='-')||(str1D=='-'&&str2D=='+')){
            int up =0;
            char maxD,minD;
            String maxstr,minstr;
            if (str1L>str2L){
                maxstr = str1;
                maxD = str1D;
                minstr = str2;
                minD = str2D;
            }else if (str1L<str2L){
                maxstr = str2;
                maxD = str2D;
                minstr = str1;
                minD = str1D;
            }else {
                if (str1.compareTo(str2)>0){
                    maxstr = str1;
                    maxD = str1D;
                    minstr = str2;
                    minD = str2D;
                }else {
                    maxstr = str2;
                    maxD = str2D;
                    minstr = str1;
                    minD = str1D;
                }
            }
            int i=maxstr.length()-1,j=minstr.length()-1;

            for (;i>=0&j>=0;i--,j--){
                int temp = Integer.parseInt(String.valueOf(maxstr.charAt(i)))-Integer.parseInt(String.valueOf(minstr.charAt(j)))+up;
                if (temp >=0){
                    result.append(temp);
                    up = 0;
                }else {
                    temp = temp+10;
                    up = -1;
                    result.append(temp);
                }
            }
            //System.out.println("\""+result.reverse().toString()+"\"");
            while (i>=0){
                int temp = Integer.parseInt(String.valueOf(maxstr.charAt(i)))+up;
                if (temp >=0){
                    result.append(temp);
                    up = 0;
                }else {
                    temp = temp+10;
                    up = -1;
                    result.append(temp);
                }
                i--;
            }
            if (maxD == '-'){
                result.append('-');
            }
            System.out.println("\""+Integer.parseInt(result.reverse().toString())+"\"");

        }else {
            int up = 0;
            int i=str1L,j=str2L;
            for (i=str1L-1,j=str2L-1;i>=0&&j>=0;i--,j--){
                int temp = Integer.parseInt(String.valueOf(str1.charAt(i)))+Integer.parseInt(String.valueOf(str2.charAt(j)))+up;
                up = temp/10;
                result.append(temp%10);
            }
            //System.out.println("\""+result.reverse().toString()+"\"");
            while (i>=0){
                int temp = Integer.parseInt(String.valueOf(str1.charAt(i)))+up;
                up = temp/10;
                result.append(temp%10);
                i--;
            }
            while (j>=0){
                int temp = Integer.parseInt(String.valueOf(str2.charAt(j)))+up;
                up = temp/10;
                result.append(temp%10);
                j--;
            }
            if (up != 0)result.append(up);
            System.out.println("\""+result.reverse().toString()+"\"");
        }
    }
}

发表于 2021-07-21 19:41:12 回复(0)
我的思路是:首先控制台输入两个带双引号得字符串,所以输入得时候用转义字符\*进行转换,因为我们需要进行加法,所以去掉“”,故用replace将\*替换为空。之后将得到的新字符串进行转换成int类型。最后相加。欢迎大佬们指正
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while (sc.hasNext()) {
            String a = "\"" + sc.next() + "\"";
            String b = "\"" + sc.next() + "\"";
            String e = a.replace("\"", "");
            String f = b.replace("\"", "");
            int c = Integer.parseInt(e);
            int d = Integer.parseInt(f);
            int result = 0;
            if (c < 0 && d > 0 && d > c) {
                result = c + d;
            }else if (c>=0&&d>=0){
                result=c+d;
               
            }else if(c>=0&&d<=0){
                result=c+d;
                
            }else if(c<=0&&d<=0){
                result=c+d;
            }
            System.out.println("\""+result+"\"");
        }
    }
}

发表于 2020-10-12 10:15:43 回复(0)
m = int(input()[1:-1])
n = int(input()[1:-1])
print('"'+str(m+n)+'"')

发表于 2020-09-06 21:54:02 回复(0)
str1 = input()
str2 = input()
res = '\"'
res += str(int(str1[1:-1])+int(str2[1:-1]))
res += '\"'
print(res)
发表于 2020-08-05 23:35:56 回复(0)
代码比较清晰。
#include <iostream>
#include <string>
#include <algorithm>
 
/**
 * 溢出:只有同号才会有可能是溢出,互异时直接转换为整数,相加,不会溢出。
*/
 
void add(std::string x, std::string y) {
    
  int x_len = x.length();
  int y_len = y.length();
 
  if(x.front()=='-' && y.front() !='-' ||
     x.front()!='-' && y.front() =='-') {
    // 直接相加
    std::cout<<"\""<< (std::stod(x) + std::stod(y))<<"\""<<std::endl;
    return;
  }
 
  bool negative = x.front() =='-' ? true : false;
    
  std::string result;
  result.reserve(std::max(x_len, y_len));
   
  int i=x_len-1, j=y_len-1;
  int carry=0;
 
  for(; (i >=0 && x[i] !='-') && (j>=0 && y[j] != '-'); --i, --j) {
    int num1 = x[i]-'0';
    int num2 = y[j]-'0';
 
    int sum = num1 + num2 + carry;
    carry = sum / 10;   
    result.push_back(sum % 10 +'0');
  }
   
  while(i >=0 && x[i] !='-') {
    int sum = x[i]-'0' +carry;
    carry = sum / 10;   
    result.push_back((sum % 10) +'0');
    --i;
  }
   
  while(j>=0 && y[j] != '-') {
    int sum = y[j]-'0' +carry;
    carry = sum / 10;   
    result.push_back((sum % 10) +'0');
    --j;
  }
   
  if(carry==1) {
    result.push_back('1');
  }
  std::reverse(result.begin(), result.end());
 
  std::cout<<"\"";
  if(negative)
    std::cout<<'-';
  std::cout<<result;
  std::cout<<"\"";
}
 
int main(int argc, char* const argv[]) {
  std::string x, y;
  std::cin>>x>>y;
 
  add(x.substr(1, x.length()-2), y.substr(1, y.length()-2));
  return 0;
}


发表于 2020-06-03 21:55:04 回复(0)
#include<string>
(765)#include<iostream>
using namespace std;

string sum(string& num1, string& num2) {
	bool pos1 = num1[0] != '-';
	bool pos2 = num2[0] != '-';
	int op = (pos1 ^ pos2) ? -1 : 1;
	if (num1[0] == '-' || num1[0] == '+') num1 = num1.substr(1);
	if (num2[0] == '-' || num2[0] == '+') num2 = num2.substr(1);
	if (op == -1) {
		if (num1.size() < num2.size() || (num1.size() == num2.size() && num1 < num2)) {
			swap(num1, num2);
			swap(pos1, pos2);
		}
	}
	int index = 1;
	int carry=0;
	string res="";
	while (index <= num1.size() || index <= num2.size()) {
		char c1 = '0', c2 = '0';
		if (index <= num1.size()) 
			c1 = num1[num1.size() - index];
		if (index <= num2.size()) 
			c2 = num2[num2.size() - index];
		int tmp = (c1 - '0') + op * (c2 - '0') + carry;
		carry = 0;
		if (tmp < 0) {
			tmp += 10;
			carry = -1;
		}
		if (tmp >= 10) {
			tmp -= 10;
			carry = 1;
		}
		res = to_string(tmp) + res;
		++index;
	}
	if (carry > 0) 
		res = to_string(carry) + res;
	index = 0;
	while (index < res.size() && res[index] == '0')++index;
	if (index == res.size())
		return "0";
	res = res.substr(index);
	if (!pos1)
		res = '-' + res;
	return res;
}

int main() {
	string num1, num2;
	cin >> num1 >> num2;
	num1 = num1.substr(1, num1.size() - 2);
	num2 = num2.substr(1, num2.size() - 2);
	cout <<"\""<< sum(num1, num2) << "\"" << endl;
}

编辑于 2020-05-12 20:28:15 回复(0)
sdsad
发表于 2020-05-11 22:54:41 回复(0)

public  String add(String a,String b){
        Integer aint = Integer.valueOf(a);
        Integer bint = Integer.valueOf(b);
        int result = aint + bint;
        String resultStr = String.valueOf(result);
        return resultStr;
    }

发表于 2020-04-21 17:40:10 回复(0)
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
         
        Scanner in = new Scanner(System.in);
            
        String s1 = in.next();
 
        String s2 = in.next();
         
        s1 = s1.substring(1,s1.length()-1);
         
        s2 = s2.substring(1,s2.length()-1);
 
         
        int num1 = Integer.valueOf(s1);
 
        int num2 = Integer.valueOf(s2);
 
        int sum = num1+num2;
         
        System.out.println("\"" +sum+ "\"");
    }
 
}

发表于 2020-04-17 20:31:19 回复(0)
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        String num1=sc.next();
        String num2=sc.next();
        //判断是否为负数
        int flag1=num1.charAt(1)=='-'?-1:1;
        int flag2=num2.charAt(1)=='-'?-1:1;
        int number1=0,number2=0;
        //逐一取出读取的字符,转化为数字,加上原来的数字乘以10
        for(int i=0;i<num1.length();i++){
            if(num1.charAt(i)!='\"'&&num1.charAt(i)!='-'){
                   number1=10*number1+num1.charAt(i)-'0';
               }
        }
        for(int j=0;j<num2.length();j++){
            if(num2.charAt(j)!='\"'&&num2.charAt(j)!='-'){
                   number2=10*number2+num2.charAt(j)-'0';
               }
        }
        //是负数就乘以-1
        number1=flag1==-1?number1*-1:number1;
        number2=flag2==-1?number2*-1:number2;
        System.out.println("\""+(number1+number2)+"\"");
    }
}


发表于 2020-04-10 12:46:17 回复(0)
import java.util.Scanner;

public class Main1 {
    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        String s1=scanner.nextLine();
        String s11=s1.substring(1,s1.length()-1);
        String s2 =scanner.nextLine();
        String s22=s2.substring(1,s2.length()-1);
        if (s1.length()==0 || s2.length()==0)
            System.out.println(-1);
        long a=Long.parseLong(s11);
        long b=Long.parseLong(s22);
        long c=a+b;
        System.out.println("\""+c+"\"");
    }
}

发表于 2020-04-08 23:39:15 回复(0)
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String num1 = scanner.nextLine();
    String num2 = scanner.nextLine();
    num1 = num1.replace("\"","");
    num2 = num2.replace("\"","");
    char ch1 = num1.charAt(0);
    char ch2 = num2.charAt(0);
    String res;
    if (ch1 != '-' && ch2 != '-') {
      res = addString(num1, num2);
    } else if (ch1 == '-' && ch2 == '-') {
      String sum = addString(num1.substring(1), num2.substring(1));
      res = sum == "0"? sum: "-" + sum;
    } else if (ch1 == '-'){
      if (compare(num1.substring(1), num2)) {
        String sum = subString(num1.substring(1), num2);
        res = sum == "0"? sum: "-" + sum;
      } else {
        res = subString(num2, num1.substring(1));
      }
    } else { // ch2 == '-'
      if (compare(num1, num2.substring(1))) {
        res = subString(num1, num2.substring(1));
      } else {
        String sum = subString(num2.substring(1), num1);
        res = sum == "0"? sum: "-" + sum;
      }
    }
    System.out.println("\"" + res + "\"");
  }

  // num1是否比num2大
  public static boolean compare(String num1, String num2) {
    int aLen = num1.length();
    int bLen = num2.length();
    if (aLen > bLen) {
      return true;
    } else if (aLen < bLen) {
      return false;
    } else {
      return num1.compareTo(num2) > 0 ? true: false;
    }
  }

  // 两个正数相加
  public static String addString(String num1, String num2) {
    StringBuilder res = new StringBuilder("");
    int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
    while(i >= 0 || j >= 0){
      int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;
      int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;
      int tmp = n1 + n2 + carry;
      carry = tmp / 10;
      res.append(tmp % 10);
      i--; j--;
    }
    if(carry == 1) res.append(1);
    return res.reverse().toString();
  }

  // num1 - num2 && num1 > num2
  public static String subString(String num1, String num2) {
    StringBuilder res = new StringBuilder("");
    int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
    while(i >= 0 || j >= 0){
      int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;
      int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;
      int tmp;
      if (n1 + carry < n2) {
        tmp = n1 + carry + 10 - n2;
        carry = -1;
      } else {
        tmp = n1 + carry - n2;
        carry = 0;
      }
      res.append(tmp);
      i--; j--;
    }
    String resStr = res.reverse().toString();
    int splitIndex = 0;
    boolean isAllZero = true;
    for (i=0; i < resStr.length(); i++) {
      if (resStr.charAt(i) != '0') {
        splitIndex = i;
        isAllZero =false;
        break;
      }
    }
    return isAllZero? "0": resStr.substring(splitIndex);
  }
}

发表于 2020-04-03 00:24:03 回复(0)

题有点坑 要去掉输入的引号

import java.math.BigInteger;
import java.util.*;
public class Main {

    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        String num1 = input.nextLine();
        num1=num1.substring(1,num1.length()-1);
        String num2 = input.nextLine();
        num2=num2.substring(1,num2.length()-1);
        BigInteger add=new BigInteger(num1).add(new BigInteger(num2));
        System.out.println("\""+add+"\"");
    }
}
发表于 2020-03-08 11:44:58 回复(0)