[编程题]A+B
  • 热度指数:11846 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
给定两个整数A和B,其表示形式是:从个位开始,每三位数用逗号","隔开。 现在请计算A+B的结果,并以正常形式输出。

输入描述:
输入包含多组数据数据,每组数据占一行,由两个整数A和B组成(-10^9 < A,B < 10^9)。


输出描述:
请计算A+B的结果,并以正常形式输出,每组数据占一行。
示例1

输入

-234,567,890 123,456,789
1,234 2,345,678

输出

-111111101
2346912

python

while True:
    try:
        print(sum(map(int,input().replace(",","").split())))

    except:
        break
编辑于 2019-02-28 13:49:17 回复(7)
#include<stdio.h>
#include<string.h>
long long fun(char m[]){
int i,flag=0;
long long  sum=0;
for(i=0;i<strlen(m);i++){
if(m[i]=='-'){
flag=1;
}else if(m[i]==','){
continue;
}else{
sum+=m[i]-'0';
sum*=10; 
}
}
if(flag){
return -sum/10;
}else{
return sum/10;
}
}
int main(){
char a[20],b[20];
while(scanf("%s%s",a,b)!=EOF){
printf("%lld\n",fun(a)+fun(b));
}
return 0;

发表于 2017-03-18 12:24:56 回复(0)
#include <iostream>
#include <string>
using namespace std;

int translate(string str);

int translate(string str){
    int num=0,i;
    for(i=0;i<str.size();i++){
        if(str[i]=='-'||str[i]==',')
            continue;        
        num=num*10+(str[i]-'0');
    }
    if(str[0]=='-') return -num;
    else return num;
}

int main(){
    string a,b;
    while(cin>>a>>b){
        cout<<translate(a)+translate(b)<<endl;
    }
    return 0;
}
发表于 2017-11-29 19:02:08 回复(0)
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while(scanner.hasNext()){
			String strNum1 = scanner.nextLine();
			String[] num = 	strNum1.split(" ");
			long num1 = Long.valueOf(num[0].toString().replace(",",""));
			long num2 = Long.valueOf(num[1].toString().replace(",",""));
			System.out.println(num1+num2);
		}
	}
}


发表于 2017-04-06 10:25:14 回复(0)
#include <cstdio>
#include <cstring> 
void NormalSum(char *longer, char *shorter){
	int longerIndex = strlen(longer)-1;
	int shorterIndex = strlen(shorter)-1;
	int cf = 0;
	while(shorterIndex>=0){
		if(shorter[shorterIndex] == '-')
			break;
		if(shorter[shorterIndex] == ','){
			shorterIndex--;
			continue;
		}
		if(longer[longerIndex]==','){
			longerIndex--;
			continue;
		}
		int temp = longer[longerIndex] + shorter[shorterIndex] -'0'*2 + cf;
//		printf("%c+%c = %d", longer[longerIndex], shorter[shorterIndex], temp);
		if(temp>=10){
			cf = 1;
			temp -= 10;
		}
		else{
			cf = 0;
		}
		longer[longerIndex] = temp + '0';
//		printf(" and the result in the longer[longerIndex] is %c", longer[longerIndex]);
		longerIndex--;
		shorterIndex--;
	}
	while(longerIndex>=0){
		if(longer[longerIndex] == '-')
			break;
		if(longer[longerIndex] == ','){
			longerIndex--;
			continue;
		}
		int temp = longer[longerIndex] + cf - '0';
		if(temp>=10){
			cf = 1;
			temp -= 10;
		}
		else{
			cf = 0;
		}
		longer[longerIndex] = temp + '0';
		longerIndex--;
	}
	if(longer[longerIndex] == '-')
		printf("-");
	if(cf == 1)
		printf("1");
	int SkipZerosFlag = 0;
	for(int i=0; i<strlen(longer); i++){
		while(SkipZerosFlag == 0 && i<strlen(longer)){
			if(longer[i]=='0' || longer[i]==',')
				i++;
			else
				SkipZerosFlag =1;
		}
		if(i>=strlen(longer))
			break;
		if(longer[i] == '-' || longer[i] == ',')
			continue;
		printf("%c", longer[i]);
	}
	puts("");
}
void longerMinusShorter(char *longer, char *shorter){
	int longerIndex = strlen(longer)-1;
	int shorterIndex = strlen(shorter)-1;
	int cf = 0;
	while(shorterIndex >= 0){
		if(shorter[shorterIndex] == '-')
			break;
		if(shorter[shorterIndex] == ','){
			shorterIndex -- ;
			continue;
		}
		if(longer[longerIndex] == ','){
			longerIndex --;
			continue;
		}
		int temp = longer[longerIndex] - shorter[shorterIndex] - cf;
		if(temp < 0){
			cf = 1;
			temp += 10;
		}
		else{
			cf = 0;
		}
		longer[longerIndex] = temp +'0';
		longerIndex--;
		shorterIndex--;
	}
	while(longerIndex>=0){
		if(longer[longerIndex]=='-')
			break;
		if(longer[longerIndex]==','){
			longerIndex--;
			continue;
		}
		int temp = longer[longerIndex] - '0' - cf;
		if(temp <0){
			cf = 1;
			temp += 10;
		}
		else{
			cf =0;
		}
		longer[longerIndex--] = temp +'0';
	}
	for(int i=0; i<strlen(longer); i++){
		if(longer[i]==',')
			continue;
		printf("%c", longer[i]);
	}
	puts("");
}
void sameSi***us(char *positive, char *negative){
	int index = strlen(positive)-1;
	int cf = 0;
	while(index>=0){
		if(positive[index]==','){
			index --;
			continue;
		}
//		printf("%c-%c=",positive[index], negative[index]);
		int temp = positive[index] - negative[index] - cf;
//		printf("%d", temp);
		if(temp<0){
			cf = 1;
			temp+=10;
		}
		else{
			cf = 0; 
		}
//		printf("%d \n", temp);
		positive[index--] = temp + '0';

	} 
	if(cf==1){
		printf("-");
		for(int i =0; i<strlen(positive); i++){
			if(positive[i] == ',')
				continue;
			positive[i] = '9'-positive[i] +'0';
		}
		NormalSum(positive, "1");
		
	}
	else{
	
		int skipZeroFlag = 0;
		for(int i=0; i<strlen(positive);i++){
			while(skipZeroFlag==0){
				if(positive[i] == '0'|| positive[i] == ','){
					i++;
				} 
				else{
					skipZeroFlag =1;
				}
				if(i==strlen(positive)){
					printf("0");
					break;
				}
			}
			if(positive[i] == ',' || i>=strlen(positive))
				continue;
				
			printf("%c", positive[i]);
		}
		puts("");
	}
	
}
void minus(char *positive, char *negative){
	if(strlen(positive)>strlen(negative)-1){
		longerMinusShorter(positive, negative);
	} else if(strlen(positive) < strlen(negative)-1){
		longerMinusShorter(negative, positive);
	}
	else {
		char newNeg[100];
		for(int i=0; i<strlen(negative)-1; i++){
			newNeg[i] = negative[i+1];
		}
		sameSi***us(positive, newNeg);
	}
}
int main(){
	char a[100], b[100];
	while(scanf("%s %s", a, b)!=EOF){
		if((a[0]=='-'&&b[0]=='-')||(a[0]!='-'&&b[0]!='-')){
			if(strlen(a)>strlen(b))
				NormalSum(a, b);
			else
				NormalSum(b, a);
		}
		else if(b[0]=='-')
			minus(a, b);
		else
			minus(b, a);
	}
}

无语,原来最后的结果是可以以int返回的。
我写的字符串相加减,一共分为三种情况:1. 同号相加 2. 异号时整数部分同等长度相减 3. 异号时整数部分长的减短的。
一些需要注意的点:
1. 要跳过开头多余的0.
2. 第二种情况下如果计算结果为负,则应该每一位进行反转,即整数部分再次加1操作。
3. 一定要搞清楚什么时候应该加'0' 减'0'。

发表于 2022-03-07 12:23:27 回复(0)
#include<stdio.h>//1.字符数组转整数数组 2.整数数组转整数
#include<string.h>
#include<math.h>
int change(char n[])
{
    int num1,i,j,a[15],fushu=0;
    num1=strlen(n);
    //1.字符数组转换成整数数组
    for(i=num1-1,j=0;i>=0;i--)//倒序存放方便计算个位放在a[0]
    {
        if(n[i]!=','&&n[i]!='-')//仅为数字的时候转换并且下标加1
            a[j++]=n[i]-'0';
        else      //若为, 或者- 此时不放在整数数组,并且数组长度减一
            num1--;//位数-1
        if(n[i]=='-') fushu=1;//判断是否是素数
    }
    //2.整数数组转换成整数
    int sum=0;
    for(i=0;i<num1;i++)//i=0是个位的数字        
          sum+=a[i]*pow(10,i);
    if(fushu) sum=sum*(-1);//把数转换成负数
    return sum;
}
int main()
{
    char n1[15],n2[15];int m,n;
    scanf("%s%s",n1,n2);
    m=change(n1);n=change(n2);
    printf("%d\n",m+n);
}

编辑于 2020-03-30 16:35:06 回复(1)
Java 解法
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        //Java int 类整数的最大值是 2147483647 满足题目条件
        Scanner scanner = new Scanner(System.in);
        System.out.println(getNum(scanner.next())+getNum(scanner.next()));
    }
    
    public static int getNum(String s){
        String s1 = s.replace(",", "");
        return s1.startsWith("-")?-Integer.parseInt(s1.substring(1)):Integer.parseInt(s1);
    }
}


发表于 2020-03-17 10:03:45 回复(0)
/** \brief 处理字符串的相关函数很有用
 *
 * \param 
 * \param 
 * \return 
 *
 */     

#include <iostream>
#include <string>
using namespace std;
string& remove_pun(string& str){
    string::size_type pos=0;
    while((pos=str.find(',',pos))!=string::npos){
        str.erase(pos,1);
        ++pos;
    }
    return str;
}

int main(){
    int a,b;
    string s1,s2;
    while(cin>>s1>>s2){
        s1=remove_pun(s1);
        s2=remove_pun(s2);
        a=stoi(s1);
        b=stoi(s2);
        cout<<a+b<<endl;
    }
    return 0;
}

编辑于 2020-03-11 18:06:40 回复(0)
#include <iostream>
#include <string>
using namespace std;

int main(){
	string str1,str2;
	while(cin>>str1>>str2){
		for(int i(str1.size()-1);i>=0;--i){
			if(str1[i]== ',')
				str1.erase(i,1);
		}
		for(int i(str2.size()-1);i>=0;--i){
			if(str2[i]== ',')
				str2.erase(i,1);
		}

		cout<<stol(str1)+stoi(str2)<<endl;
	}
    return 0;
}

编辑于 2020-03-05 12:49:26 回复(0)
#include <iostream>
#include <algorithm>
using namespace std;

int to_int(string a)
{
    a.erase(remove(a.begin(), a.end(), ','), a.end());
    return stoi(a);
}

int main()
{
    string a, b;
    while (cin >> a >> b)
    {
        cout << to_int(a) + to_int(b) << endl;
    }
    
}

发表于 2020-02-07 17:58:12 回复(0)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100
double number(char *);
int main(){
    char a[N],b[N];
    double A,B;
    scanf("%s%s",a,b);
    A=number(a);
    B=number(b);
    printf("%d",(int)(A+B));
}
double number(char *a){
    int i,flag=0;
    double b=0;
    if(a[0]=='-'){
        i=1;
        while(a[i]!='\0'){
            if(a[i]==','){
                i++;
                continue;
            }
            b=b*10+(double)(a[i]-'0');
            i++;
        }
        b=-b;
        return b;
    }
    else {
        i=0;
        while(a[i]!='\0'){
            if(a[i]==','){
                i++;
                continue;
            }
            b=b*10+(double)(a[i]-'0');
            i++;
        }
    }
    return b;
}
发表于 2020-01-06 18:31:04 回复(0)
#include <iostream>
#include <string>
using namespace std;
int s2l(string x)
{
    int m=x.length();
    long long y=0;
    for(int i=0;i<m;i++)
    {
        if(x[i]!='-' && x[i]!=',')
        {
            y*=10;y+=x[i]-'0';
        }
    }
    if(x[0]=='-')
        y*=-1;
    return y;
}
int main()
{
    string A,B;
    while(cin>>A>>B)
    {
        cout<<s2l(A)+s2l(B)<<endl;
    }
    return 0;
}
发表于 2019-08-18 11:16:46 回复(0)
import java.util.Scanner;
public class Main{
    /*
    不用重复造轮子就是方便啊哈哈
    */
    public static void main(String[] args){
        try(Scanner in = new Scanner(System.in)){
            String s1 = in.next(),s2 = in.next();
            System.out.println(helper(s1,s2));
        }
    }
    public static int helper(String s1,String s2){
        String[] str1 = s1.split(","),str2 = s2.split(",");
        StringBuffer sb1 = new StringBuffer(),sb2 = new StringBuffer();
        for(String s:str1){
            sb1.append(s);
        }
        for(String s:str2){
            sb2.append(s);
        }
        int num1 = Integer.valueOf(sb1.toString()),num2 = Integer.valueOf(sb2.toString());
        return num1 + num2;
    }
}


发表于 2019-01-13 22:02:06 回复(0)
#include<stdio.h>
#include<string.h>

int str2num(char a[]){
    int j,i=0;
    int s=0;
    int n=strlen(a);
    if(a[0]=='-')
        i++;
    for(j=i;j<n;j++){
        if(a[j]!=','){
            s=s*10+(a[j]-'0');
        }
    }
    if(a[0]=='-')
        return -s;
    else
        return s;
}
int main(){
    char a[13];
    char b[13];
    scanf("%s",&a);
    scanf("%s",&b);
    printf("%d",str2num(a)+str2num(b));
    return 0;
}
发表于 2018-06-03 11:27:28 回复(0)
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll change(char str[],int s,int e) {
    ll num = 0;
    for(int i = s;i <= e;i++) {
        if(str[i] != ',') {
            num *= 10;
            num += str[i] - '0';
        }
    }
    return num;
}
int main() {
    char num1[12];
    char num2[12];
    ll t1,t2,sum = 0;
    while(scanf("%s%s",num1,num2) == 2) {
        int len1 = strlen(num1);
        int len2 = strlen(num2);
        if(num1[0] == '-') {
            t1 = change(num1,1,len1 - 1);
            t1 = 0 - t1;
        }
        else {
            t1 = change(num1,0,len1 - 1);
        }
        if(num2[0] == '-') {
            t2 = change(num2,1,len2 - 1);
            t2 = 0 - t2;
        }
        else {
            t2 = change(num2,0,len2 - 1);
        }
        sum = t1 + t2;
        printf("%lld\n",sum);
    }
}
发表于 2018-03-29 16:12:59 回复(0)
虽然知道题目的意图,但是就是想用BigInteger做。
            String line = sin.nextLine();
            String[] nums = line.split(" ");
            String[] k1 = nums[0].split(",");
            String[] k2 = nums[1].split(",");
            String a = "";
            String b = "";
            for(int i = 0;i<k1.length;i++){
                a += k1[i];
            }
            for(int i = 0;i<k2.length;i++){
                b += k2[i];
            }
            BigInteger ba = new BigInteger(a);
            BigInteger bb = new BigInteger(b);
            BigInteger br = ba.add(bb);
            System.out.println(br);

发表于 2017-05-30 19:32:39 回复(0)
#include<iostream>
#include<string.h>
using namespace std;

int main()
 {
       char a[100],b[100];
       while(cin>>a>>b)
         {
            int m=0,n=0,SUM;
            int flag1=0,flag2=0;  //记录两个数字a,b的正负(0正1负)
            long k1=10,k2=10;
            int len1=strlen(a);   //得到两个字符串的长度,如strlen(-2,223)=6
            int len2=strlen(b);
			long sum1=a[len1-1]-'0',sum2=b[len2-1]-'0';  //为了方便,先将个位存入到sum中,也就是两个字符串的最后一位
            for(int i=len1-2;i>=0;i--)  //从倒数第二位及以后(非'-'和‘,’)开始累加
               {
                  if(a[i]=='-')
                      flag1=1;
                  if((a[i]!=',')&&(a[i]!='-'))
                     {                       
                       sum1+=(a[i]-'0')*k1;
                       k1*=10;
                     }
               } 
           if(flag1==1)
                sum1=0-sum1;
            
           for(int i=len2-2;i>=0;i--)
               {
                  if(b[i]=='-')
                      flag2=1;
                  if((b[i]!=',')&&(b[i]!='-'))
                     {
                       sum2+=(b[i]-'0')*k2;
					   k2*=10;
                     }
               } 
            if(flag2==1)
                sum2=0-sum2;
           
           SUM=sum1+sum2;
           cout<<SUM<<endl;
           
         }   
 }
编辑于 2017-05-10 09:23:43 回复(0)
我这样也能通过,我怎么感觉我这么写有问题,尴尬

import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
	  Scanner sc=new Scanner(System.in);
	  while(sc.hasNext()){
		  int a1=sc.nextInt();
		  int a2=sc.nextInt();
		  System.out.println(a1+a2);
	  }	  
   }
}


发表于 2017-04-11 10:04:24 回复(0)

这题最好通过valueOf()来做~~

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            fun(in.nextLine());
        }
        in.close();
    }
    public static void fun(String str){
        StringBuffer stra = null,strb = null;
        for(int i = 0; i < str.length(); i++){
            if(str.charAt(i) == ' '){
                stra = new StringBuffer(str.substring(0, i));
                strb = new StringBuffer(str.substring(i+1));
                break;
            }
        }
        for(int i = 0; i < stra.length(); i++)
            if(stra.charAt(i) == ',')
                stra.deleteCharAt(i);
        for(int i = 0; i < strb.length(); i++)
            if(strb.charAt(i) == ',')
                strb.deleteCharAt(i);

        System.out.println(Long.valueOf(stra.toString())+Long.valueOf(strb.toString()));
    }
}
发表于 2017-02-06 17:18:25 回复(0)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

// 处理数据
int solve(string str)
{
    int tmp = 0;
    for(int i = 0; i < str.length(); ++i)
    {
        if(str[i] == ',' || str[i] == '-')
        {
            continue;
        }
        else
        {
            tmp = tmp*10 + (str[i]-'0');
        }
    }
    if(str[0] != '-') return tmp;
    else return -tmp;
}

int main()
{
    
    int a, b;
    string str1, str2;
    while(cin >> str1 >> str2)
    {
        a = solve(str1);
        b = solve(str2);
        cout << a+b << endl;
    }

    return 0;
}


发表于 2016-08-07 11:13:05 回复(7)

问题信息

难度:
132条回答 10492浏览

热门推荐

通过挑战的用户

查看代码