首页 > 试题广场 >

整数加法

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

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

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


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

输入

123 123
abd 123

输出

246
error
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)
利用StringBuilder逆序按位算和就可以了
前排吐槽:用例给的是Error,然后题目中给的是error,提交错到这里太离谱了,也是我太不用心了
import java.util.*;
import java.math.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    int res = 0;
    public static void main (String[] args) throws IOException{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while ((str = bf.readLine()) != null) {
            String[] s = str.split(" ");
            String s1 = new StringBuilder(s[0]).reverse().toString();
            String s2 = new StringBuilder(s[1]).reverse().toString();
            int index = 0;
            boolean f = true;
            boolean flag = false;
            StringBuilder sb = new StringBuilder();
            while (f && index < s1.length() && index < s2.length()) {
                char ch1 = s1.charAt(index);
                char ch2 = s2.charAt(index);
                if (!Character.isDigit(ch1) || !Character.isDigit(ch2)) {
                    System.out.println("error");
                    f = false;
                    break;
                }
                int ten = ch1 - '0' + ch2 - '0';
                if (flag) {
                    ten++;
                    flag = false;
                }
                flag = ten >= 10?true:false;
                sb.append(ten % 10);
                index++;
            }
            while (f && index < s1.length()) {
                char ch1 = s1.charAt(index);
                if (!Character.isDigit(ch1)) {
                    System.out.println("error");
                    f = false;
                    break;
                }
                int ten = ch1 - '0';
                if (flag) {
                    ten++;
                    flag = false;
                }
                flag = ten >= 10?true:false;
                sb.append(ten % 10);
                index++;
            }
            while (f && index < s2.length()) {
                char ch2 = s2.charAt(index);
                if (!Character.isDigit(ch2)) {
                    System.out.println("error");
                    f = false;
                    break;
                }
                int ten = ch2 - '0';
                if (flag) {
                    ten++;
                    flag = false;
                }
                flag = ten >= 10?true:false;
                sb.append(ten % 10);
                index++;
            }
            if (flag) {
                sb.append(1);
            }
            if (f) {
                System.out.println(sb.reverse().toString());
            }
        }
    }
}
运行时间:7ms
占用内存:9236KB


编辑于 2020-12-24 10:29:56 回复(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)

import java.util.Scanner;

public class Main {     public static void main(String[] args) {         String[] s = new Scanner(System.in).nextLine().split(" ");         String a;         String b;                  if(s[0].length()>s[1].length()){             a=s[0];             b=s[1];         }else{             a=s[1];             b=s[0];         }         if((!a.matches("^[0-9]*$")) || (!b.matches("^[0-9]*$"))){             System.out.println("error");return;         }         int c=a.length()-b.length();         for (int i = 0; i <c ; i++) {             b = "0" + b;         }         String result="";         int t=0,i=a.length();         while(i>0){             i--;             int r=a.charAt(i)+b.charAt(i)-'0'-'0'+t;             result=""+(r%10)+result;             t=r/10;         }                  System.out.println((t==0?"":t)+result);     }
}

发表于 2018-11-06 09:42:05 回复(0)
//这上面的编译器无法识别包 是最无语的
import java.util.Scanner;
import java.math.BigInteger;

/**
 * Created by Administrator on 2017/8/8.
 */
public class test {

    public static String  add(String a,String b){
        for(int i=0;i<a.length();i++){//检查s1是否满足数字要求
            if(!(a.charAt(i)>='0'&&a.charAt(i)<='9')){
                return "error";
            }
        }

        for(int i=0;i<b.length();i++){//检查s2是否满足数字
            if(!(b.charAt(i)>='0'&&b.charAt(i)<='9')){
                return "error";
            }
        }
        BigInteger s1 = new BigInteger(a);
        BigInteger s2 = new BigInteger(b);
        s1=s1.add(s2);//a加上b,会有返回值的,返回的是BigInteger
        return s1.toString();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()){
            String s=sc.nextLine();
            String [] str=s.split(" ");
            System.out.println(add(str[0],str[1]));
        }
    }

}
        

    


发表于 2018-09-07 17:15:10 回复(0)
public class Test11 { public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);  String c[] = scanner.nextLine().split(" ");  char a[] = c[0].toCharArray();  char b[] = c[1].toCharArray();  int jingwei = 0;  ArrayList<Integer> list = new ArrayList<>();  if (a.length>=b.length){ add(a, b, jingwei, list);  } else{ add(b, a, jingwei, list);  } for (int i=list.size()-1;i>=0;i--)
        System.out.print(list.get(i));  } private static boolean add(char[] a, char[] b, int jingwei, ArrayList<Integer> list) { for (int i=a.length-1,j=b.length-1;i>=0;i--,j--){ if (j>=0){ if (a[i]>'9'||a[i]<'0'||b[j]>'9'||b[j]<'0'){
                    System.out.println("error");  return true;  }
                list.add((a[i]-'0'+b[j]-'0'+jingwei)%10);  jingwei =(a[i]-'0'+b[j]-'0'+jingwei)/10;  } else { if (a[i]>'9'||a[i]<'0'){
                    System.out.println("error");  return true;  }
                list.add((a[i]-'0'+'0'-'0'+jingwei)%10);  jingwei =(a[i]-'0'+'0'-'0'+jingwei)/10;  } if (i==0&&jingwei!=0){
                list.add(jingwei);  }
        } return false;  }
}
发表于 2018-09-01 10:28:59 回复(0)
import java.util.*;
public class Main{
      public static void main(String[] args) {
          Scanner input=new Scanner(System.in);
             while(input.hasNext()){
                 char[] s1=input.next().trim().toCharArray();
                 char[] s2=input.next().trim().toCharArray();
                Stack stack1=new Stack();
                Stack stack2=new Stack(); 
                for(int i=0;i<s1.length;i++){
                     int cur=0;
                    try{
                          cur=Integer.parseInt(String.valueOf(s1[i]));
                    }catch(Exception e){
                         System.out.println("error");
                         return;
                    }
                        stack1.push(cur);
                }
                  for(int i=0;i<s2.length;i++){
                        int cur=0;
                     try{
                         cur=Integer.parseInt(String.valueOf(s2[i]));
                    }catch(Exception e){
                         System.out.println("error");
                         return;
                    }
                        stack2.push(cur);
                }

                 Stack res=new Stack();
                 int a=0;   //进位标志
                 while(!stack1.isEmpty()||!stack2.isEmpty()){
                     int a1=0;
                     if(!stack1.isEmpty()){
                         a1=stack1.pop();
                     }
                      int a2=0;
                     if(!stack2.isEmpty()){
                         a2=stack2.pop();
                     }

                     int cur=a1+a2+a;
                     if(cur>=10){
                         cur=cur%10;
                         a=1;
                         res.push(cur);
                     }else{
                          res.push(cur);
                          a=0;
                     }
                 }
                 //最后还要判断最高位是不是进位了
                 if(a==1){
                     res.push(a);
                 }
                 StringBuilder sb=new StringBuilder();
                 while(!res.isEmpty()){
                     sb.append(res.pop());
                 }
                 System.out.println(sb.toString());
         }

   }
}

发表于 2018-08-05 09:23:54 回复(0)
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)

运行时间:59ms
占用内存:9984k
一开始直接用的Integer,报case通过率80%,发现是输入的串很多个1超过了Integer范围,继续导入java.math.BigInteger搞定。

import java.math.BigInteger;
import java.util.Scanner;
public class Main {
    public static boolean is1(String str) {
        for(int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if(c >= '0' && c <= '9') {
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()) {
            String str = scan.nextLine();
            String[] arr = str.split(" ");
            if(is1(arr[0]) && is1(arr[1])) {
                BigInteger a = new BigInteger(arr[0]); 
                BigInteger b = new BigInteger(arr[1]);
                System.out.println(a.add(b));
            }
            else {
                System.out.println("error");
            }
        }
    }
}

看下面分析的,针对「abc123 123」这样的输入也会返回「error」的优化后的code:

import java.math.BigInteger;
import java.util.Scanner;
public class Main {
    public static boolean is1(String str) {
        int count = 0;
        for(int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if(c >= '0' && c <= '9') {
                count++;
                if(count == str.length()) {
                    count = 0;
                    return true;
                }
            }
        }
        return false;
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()) {
            String str = scan.nextLine();
            String[] arr = str.split(" ");
            if(is1(arr[0]) && is1(arr[1])) {
                BigInteger a = new BigInteger(arr[0]); 
                BigInteger b = new BigInteger(arr[1]);
                System.out.println(a.add(b));
            }
            else {
                System.out.println("error");
            }
        }
    }
}

两段代码都通过了OJ。

编辑于 2018-04-13 13:40:30 回复(2)

import java.util.Scanner
比短是比不过Python的,这辈子也比不过。
public class Main {
    public static void main(String[] args) {
        try {
            Scanner input = new Scanner(System.in);
            System.out.print(input.nextBigInteger().add(input.nextBigInteger()));
        } catch (Exception e) {
            System.out.print("error");
        }
    }
}

发表于 2018-04-10 13:48:37 回复(0)
import java.util.Stack;
import java.util.Scanner;
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 = getSumString(ss[0], ss[1]);
            System.out.println(result);
        }
    }
    public static String getSumString(String a ,String b) {
            char[] s1 = a.toCharArray();
            char[] s2 = b.toCharArray();
            Stack<Integer> stack1 = new Stack<Integer>();
            Stack<Integer> stack2 = new Stack<Integer>();
            for(int i = 0 ; i< s1.length ; i++) {
                if(new Integer(s1[i]) < 48 || new Integer(s1[i]) > 57) {
                    return "error";
                }
                stack1.push(new Integer(String.valueOf(s1[i])));
            }
            for(int i = 0 ; i< s2.length ; i++) {
                 if(new Integer(s2[i]) < 48 || new Integer(s2[i]) > 57) {
                    return "error";
                }
                stack2.push(new Integer(String.valueOf(s2[i])));
            }
            int k = 0;
            Stack<Integer> stack3 = new Stack<Integer>();
            while (!stack1.empty() || !stack2.empty()) {
                Integer i = 0;
                Integer j = 0;
                if(!stack1.empty()) {
                    i = stack1.pop();
                }
                if(!stack2.empty()) {
                    j = stack2.pop();
                }
                if(i != null) {
                    k += i;
                }
                if(j != null) {
                    k += j;
                }
                stack3.push(k%10);
                if(stack1.empty() && stack2.empty()) {
                    int s = k/10;
                    if (s > 0) {
                        stack3.push(s);
                    }
                }
               
                if(k > 9) {
                    k = 1;
                } else {
                    k = 0;
                }
            }
            StringBuffer stringBuffer = new StringBuffer();
            while (!stack3.empty()) {
                stringBuffer.append(stack3.pop());
            }
            return stringBuffer.toString();
        }
}

发表于 2018-03-23 11:19:43 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String string = null;
        while ((string = br.readLine()) != null) {
            //判断输入的字符串是否合法,如果合法则只包含数字和空格
            boolean flag = false;
            for (int i = 0; i < string.length(); i++) {
                char ch = string.charAt(i);
                if (ch != ' ' && (ch <= '0' || ch >= '9'))
                    flag = true;
            }

            if (flag) {
                System.out.println("error");
                continue;
            }
            //合法进行相加,因为数比较大,用int数组来存储数据
            String[] strings = string.split(" ");
            String s1, s2;
            if (strings[0].length() > strings[1].length()) {
                s1 = strings[0];
                s2 = strings[1];
            } else {
                s1 = strings[1];
                s2 = strings[0];
            }
            int[] result = new int[101];
            int k = 0;
            int sum = 0;
            int add = 0;
            int len1 = s1.length();
            int len2 = s2.length();
            while (k < len2) {
                sum = (s1.charAt(len1-1-k)-'0') + (s2.charAt(len2 - 1- k)-'0') + add;
                if (sum < 10) {
                    result[k] = sum;
                    add = 0;
                } else {
                    result[k] = sum - 10;
                    add = 1;
                }
                k++;
            }

            while (k < len1) {
                sum = (s1.charAt(len1 - 1 - k) - '0') + add;
                if (sum < 10) {
                    result[k] = sum;
                    add = 0;
                } else {
                    result[k] = sum - 10;
                    add = 1;
                }
                k++;
            }
            if (add == 1) {
                result[k] = 1;
            } else {
                k--;
            }
            while (k >= 0) {
                System.out.print(result[k]);
                k--;
            }
            System.out.println();
        }

    }
}
发表于 2018-03-18 16:19:08 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            String n1 = new StringBuffer(sc.next()).reverse().toString();
            String n2 = new StringBuffer(sc.next()).reverse().toString();
            String result = "";
            int overflow = 0;
            int i = 0;
            while(i <= Math.max(n1.length(), n2.length())) {
                if(i == Math.max(n1.length(), n2.length())) {
                    if(overflow != 0) result = overflow + result;
                    break;
                }
                int num1 = 0, num2 = 0;
                if(i < n1.length()) num1 = n1.charAt(i) - '0';
                if(i < n2.length()) num2 = n2.charAt(i) - '0';
                if(num1 < 0 || num1 > 9 || num2 < 0 || num2 > 9) {
                    result = "error";
                    break;
                }
                int sum = num1 + num2 + overflow;
                result = (sum % 10) + result;
                overflow = sum / 10;
                ++i;
            }
            System.out.println(result);
        }
    }
}
发表于 2018-01-13 23:36:32 回复(0)
//这题让我知道有BigInteger的存在
import java.math.BigInteger;
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        try {
            BigInteger num1 = in.nextBigInteger();
            BigInteger num2 = in.nextBigInteger();
            System.out.println(num2.add(num1));
        } catch (Exception e) {
            System.out.println("error");
        }
    }
}
----------------------------------------------------------------------
//自己实现大数的相加
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String regex = "\\d+";
        while (in.hasNext()) {
            StringBuilder str1 = new StringBuilder(in.next());
            StringBuilder str2 = new StringBuilder(in.next());
            if (str1.toString().matches(regex) && str2.toString().matches(regex)) {
                //合法输入
                processLen(str1, str2);
                String res = add(str1, str2);
                System.out.println(res);
            } else {
                System.out.println("error");
            }
        }
    }
    private static void processLen(StringBuilder str1, StringBuilder str2) {
        int len1 = str1.length(), len2 = str2.length();
        if (len1 > len2)
            for (int i = 0; i < len1 - len2; i++) str2.insert(0, "0");
        else
            for (int i = 0; i < len2 - len1; i++) str1.insert(0, "0");
    }
    private static String add(StringBuilder str1, StringBuilder str2) {
        StringBuilder res = new StringBuilder();
        int reminder = 0;
        int sum = 0;
        for (int i = str1.length() - 1; i >= 0; i--) {
            sum = str1.charAt(i) + str2.charAt(i) - 2 * '0' + reminder;
            reminder = sum / 10;
            if (i > 0)
                res.append(sum % 10);
            else {
                res.append(sum % 10);
                if (reminder > 0) res.append(1);
            }
        }
        return res.reverse().toString();
    }
}
------------------------------------------------------------------------
import java.math.BigInteger;
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String regex = "[+-]?\\d+";
        while (in.hasNext()) {
            String str1 = in.next();
            String str2 = in.next();
            if (str1.matches(regex) && str2.matches(regex)) {
                BigInteger num1 = new BigInteger(str1);
                BigInteger num2 = new BigInteger(str2);
                System.out.println(num2.add(num1));
            } else {
                System.out.println("error");
            }
        }
    }
}

编辑于 2017-12-26 13:55:37 回复(0)
import java.util.Scanner;  public class Main
{ public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);  while (scanner.hasNext()) {
            String[] strings = scanner.nextLine().split(" ");  String string1 = strings[0];  String string2 = strings[1];  String str1;  String str2;  int length1 = string1.length();  int length2 = string2.length();  int a;  int b;  int c;  int temp = 0;  StringBuffer sb = new StringBuffer();  StringBuffer sb2 = new StringBuffer();  int x;  int y;  for (x = 0; x < length1; x++) { if (string1.charAt(x) < 48 || string1.charAt(x) > 57) { break;  }
            } for (y = 0; y < length2; y++) { if (string2.charAt(y) < 48 || string2.charAt(y) > 57) { break;  }
            } if (x == length1 && y == length2) { if (length1 == length2) { for (int i = length1 - 1; i >= 0; i--) {
                        a = Integer.parseInt(String.valueOf(string1.charAt(i)));  b = Integer.parseInt(String.valueOf(string2.charAt(i)));  c = (a + b + temp) % 10;  temp = (a + b + temp) / 10;  sb.append(c);  } if (temp != 0) {
                        sb.append(temp);  }
                } else { if (length1 > length2) {
                        str1 = string1;  str2 = string2;   } else { int tem = length1;  length1 = length2;  length2 = tem;  str1 = string2;  str2 = string1;  } int i = length1 - 1;  int j = length2 - 1;  for (; j >= 0; ) {
                        a = Integer.parseInt(String.valueOf(str1.charAt(i)));  b = Integer.parseInt(String.valueOf(str2.charAt(j)));  c = (a + b + temp) % 10;  temp = (a + b + temp) / 10;  sb.append(c);  if (j == 0) { if (i >= 2) {
                                sb.append(Integer.parseInt(String.valueOf(str1.charAt(i - 1))) + temp);  while (i >= 0) {
                                    sb.append(Integer.parseInt(String.valueOf(str1.charAt(i))));  i = i - 1;  } break;  } else {
                                sb.append(Integer.parseInt(String.valueOf(str1.charAt(i - 1))) + temp);  break;  }
                        } else {
                            j = j - 1;  i = i - 1;  }
                    }
                } for (int o = sb.length() - 1; o >= 0; o--) {
                    sb2.append(sb.charAt(o));  }
                System.out.println(sb2.toString());  } else {
                System.out.println("error");  }
        }
    }
}

这题主要用的想法就是小学数学的加法,超过10往前进位,我分了情况就是两个数字长度一样和不一样两种情况,还要注意非数字的情况

发表于 2017-11-30 20:27:07 回复(0)


public class Main{
    
    public static String add(String a, String b){
        
        int len1 = a.length();
        int len2 = b.length();
        //如果a的长度小于b,交换
        if (len1 < len2){
            String temp = a;
            a = b;
            b = temp;
        }
        len1 = a.length()-1;
        len2 = b.length()-1;

        StringBuilder sb = new StringBuilder();
        //carry记录进位,sum记录每一位相加的和(取模后)
        int carry = 0;
        int sum = 0;
        int x;int y;
        while (len1 >=0){
            x = a.charAt(len1)-'0';

            if (len2 >=0){
                 y = b.charAt(len2) - '0';
            }else {
                 y = 0;
            }
            //判断输入是否合法
            if (x > 9 || x<0 || y<0 || y>9){
                return "error";
            }
            sum = (x + y + carry)%10;
            carry = (x + y + carry)/10;
            len1--;len2--;
            sb.append(sum);
        }
        
        if (carry > 0){
            sb.append(carry);
        }

        return sb.reverse().toString();
    }

    public static void main(String[] args){

        Scanner in = new Scanner(System.in);

        String s[] = in.nextLine().split(" ");
        if (s.length<2) {
            System.out.println("error");
            return;
        }
        System.out.println(add(s[0],s[1]));

    }

}

发表于 2017-11-17 15:25:27 回复(0)
import java.util.Scanner;

//try-catch捕捉转换异常
public class IntegerPlus {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		StringBuilder sb = new StringBuilder();
		while (sc.hasNext()) {
			String s1 = sc.next();
			String s2 = sc.next();
			int temp1 = Math.max(s1.length(), s2.length());
			int temp2 = Math.min(s1.length(), s2.length());
			int[] jiashu = new int[temp1];// 加数集合
			int[] beijiashu = new int[temp1];// 被加数集合
			int[] jinwei = new int[temp1];// 进位数组集合
			int[] result = new int[temp1];// 结果集合
			try {// 数据转化出错,抛异常
				if (s1.length() > s2.length()) {
					for (int i = 0; i < temp1; i++)
						jiashu[i] = Integer.valueOf(String.valueOf(s1.charAt(temp1 - i - 1)));
					for (int j = 0; j < temp2; j++)
						beijiashu[j] = Integer.valueOf(String.valueOf(s2.charAt(temp2 - j - 1)));// 补0
					result[0] = (jiashu[0] + beijiashu[0]) % 10;
					jinwei[0] = (jiashu[0] + beijiashu[0]) / 10;
					sb.insert(0, result[0]);
					for (int k = 1; k < temp1; k++) {
						result[k] = (jiashu[k] + beijiashu[k] + jinwei[k - 1]) % 10;
						jinwei[k] = (jiashu[k] + beijiashu[k] + jinwei[k - 1]) / 10;
						sb.insert(0, result[k]);// 结果集合
					}
					if (jinwei[temp1 - 1] > 0)
						sb.insert(0, 1);
				} else {
					for (int i = 0; i < temp1; i++)
						jiashu[i] = Integer.valueOf(String.valueOf(s2.charAt(temp1 - i - 1)));
					for (int j = 0; j < temp2; j++)
						beijiashu[j] = Integer.valueOf(String.valueOf(s1.charAt(temp2 - j - 1)));// 补0
					result[0] = (jiashu[0] + beijiashu[0]) % 10;
					jinwei[0] = (jiashu[0] + beijiashu[0]) / 10;
					sb.insert(0, result[0]);
					for (int k = 1; k < temp1; k++) {
						result[k] = (jiashu[k] + beijiashu[k] + jinwei[k - 1]) % 10;
						jinwei[k] = (jiashu[k] + beijiashu[k] + jinwei[k - 1]) / 10;
						sb.insert(0, result[k]);// 结果集合
					}
					if (jinwei[temp1 - 1] > 0)
						sb.insert(0, 1);
				}
				System.out.println(sb.toString());
				sb.setLength(0);
			} catch (Exception e) {
				System.out.println("Error");
				sb.setLength(0);
			}
		}
	}
}
发表于 2017-10-22 12:28:20 回复(0)
需要考虑几种情况:
1.非法字符串,这里不能直接使用try-catch捕获字符串转整形异常,因为字符串长度1-100大数字,数值保存肯定是不够的;
2.两个字符串的长度比较,然后从右往左进行同位两字符转整形相加,也就是把公有的位置数进行求和,然后在超出的那块长度与carry进位进行求和,最终还需要加上carry(我这里是用string保存结果,所以我加上carry)
3.在结果中使用StringBuffer对象的reverse反转过来,因为结果是反序保存的,考虑高位有可能有0的情况,需要使用正则:replace("^[0]*","")替换掉:
最后,代码有点长,才疏学浅,使用暴力了,不过浅显易懂,大神就跳过吧!轻点
import java.util.Scanner;

public class StringUtil {

	//整数加法
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while(in.hasNext()){
			String a = in.next();
			String b = in.next();
			int len = a.length();
			int more = 0;
			if(a.length() < b.length()){
				len = b.length();
				more = 1;
			}
			boolean ok = true;
			//非法字符串判断
			for(int i=0; i<len; i++){
				if(i<a.length() && !(a.charAt(i)>='0' && a.charAt(i)<='9')){
					System.out.println("error");
					ok = false;
					break;
				}
				if(i<b.length() && !(b.charAt(i)>='0' && b.charAt(i)<='9')){
					System.out.println("error");
					ok = false;
					break;
				}
			}
			if(ok == false)
				continue;
			//字符串后半部分相加:a更长
			int carry = 0;
			String res = "";
			if(more == 0){
				for(int i=len-1,j=b.length()-1; j>=0; j--){
					int sum = Integer.valueOf(a.charAt(i--)+"") + Integer.valueOf(b.charAt(j)+"") + carry;
//					System.out.println("sum="+sum);
					carry = sum/10;
					res += sum%10;
//					System.out.println("res="+res);
//					System.out.println("carry="+carry);
				}
				for(int i=len-b.length()-1; i>=0; i--){
					int sum = Integer.valueOf(a.charAt(i)+"") + carry;
					carry = sum/10;
					res += sum%10;
//					System.out.println("res="+res);
				}
				res += carry;
				System.out.println(new StringBuffer(res).reverse().toString().replaceAll("^[0]*",""));
			}
			
			//字符串后半部分相加:b更长
			else{
				for(int i=len-1,j=a.length()-1; j>=0; j--){
					int sum = Integer.valueOf(b.charAt(i--)+"") + Integer.valueOf(a.charAt(j)+"") + carry;
//					System.out.println("sum="+sum);
					carry = sum/10;
					res += sum%10;
//					System.out.println("res="+res);
//					System.out.println("carry="+carry);
				}
				for(int i=len-a.length()-1; i>=0; i--){
					int sum = Integer.valueOf(b.charAt(i)+"") + carry;
					carry = sum/10;
					res += sum%10;
//					System.out.println("res="+res);
				}
				res += carry;
				System.out.println(new StringBuffer(res).reverse().toString().replaceAll("^[0]*",""));
			}
		}
	}
}

编辑于 2017-09-07 19:37:02 回复(0)