整数加法

请设计一个算法能够完成两个用字符串存储的整数进行相加操作,对非法的输入则返回error
输入描述:
输入为一行,包含两个字符串,字符串的长度在[1,100]。
输出描述:
输出为一行。合法情况输出相加结果,非法情况输出error
示例1
输入

123 123
abd 123
输出

246
Error

Algrithom:
input: String in=String A+" "+String B
output: String out
begin:
int res=0;// 进位
for i=A.length-1,j=B.length-1;i>=0 && j>=0;i--,j--
{
    if(A[i]>=0 && A[i]<=9 && B[j]>=0 && B[j]<=9)
       if(A[i]+B[j]+res>=10)
           res=1;
        else
           res=0;
      out=String((A[i]+B[j]+res)%10)+out;
    else
      print("error");
      break;
   }
if (res==1)
   print(1+out);
else
  print(out);
end
import java.util.Scanner;
import java.util.Stack;
public class Main{
    public static void main(String[] args){
        Scanner s=new Scanner(System.in);
        String data=s.nextLine();
        String temp[]=data.split(" ", 2);
        String out="";
        int res=0;
        for(int i=temp[0].length()-1,j=temp[1].length()-1;i>=0 && j>=0;i--,j-- ){
            if((temp[0].charAt(i)>='0' && temp[0].charAt(i)<='9') && (temp[1].charAt(j)>='0' && temp[1].charAt(j)<='9') ){
                int a=Integer.parseInt(temp[0].substring(i, i+1));
                int b=Integer.parseInt(temp[1].substring(j, j+1));
                int result=a+b+res;
                if(result>=10){
                    res=1;
                }else{
                    res=0;
                }
                out=Integer.toString(result%10)+out;
            }else{
                System.out.println("error");
                break;
            }
        }
        if(res==1){
            System.out.print("1"+out);
        }else{
            System.out.print(out);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值