HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Adding two big integers represented as strings

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
representedaddingtwobigintegersstrings

Problem

class MyClass{
    static Integer carry = 0;
    public static void main(String args[]){
        String s1 = "7654729850328997631007285998163550104";
        String s2 = "5980139243970186632651869926335829102";
        add(s1, s2);
    }

    public static void add(String a, String b){
        ArrayList res = new ArrayList();
        StringBuilder myString = null;
        int i = a.length() - 1;
        int j = b.length() - 1;
        while(true){
            int i1 = Integer.parseInt(Character.toString(a.charAt(i)));
            int i2 = Integer.parseInt(Character.toString(b.charAt(j)));
            Integer i3  = i1 + i2 + carry;
            if(i3 > 9){
                carry = 1;
                i3 = i3 - 10;
            }else carry = 0;
            res.add(i3.toString());
            i--;j--;
            if(i < 0){
                res.add(carry.toString());
                break;
            }
        }
        Collections.reverse(res);
        for(String r : res){
            System.out.print(r);
        }
    }
}


This program adds 2 numbers whose length is greater than limit of Long. I think my logic is kind of bulky. Can something be done to improve this?

Solution

Loop structure's OK, logic's reasonably good. There is obviously a Java library alternative of BigInteger, but I assume you knew that. Some efficiency issues with excessive toString() and string-ification of what could be character operations.

Here are some tips:

  • Use int where nulls are not possible, not Integer.



  • carry is only used locally -- keep it local. Referencing it outside the method can only be erroneous, so it shouldn't be visibly exposed to make that possible..



  • Carry calculation from i3 is OK here, but could in related algorithms be brittle -- it can't handle a digit-sum > 19 as the maximum carry it can produce is 1.



  • If addition completes with a carry of 0, it will output an unnecessary 0 digit.



  • If Strings are your inputs, you should probably build a String as the result via a StringBuilder -- not an ArrayList.



  • myString should be called result or sb, if you're building the result in it.



  • Build using StringBuilder in reverse order, and do it by character calculation (char) (i3 + '0') rather than toString() if you want to maximize efficiency.



  • Return the result from your function, and do the printing in main() instead. there. That way you have a general-purpose add() function and a fixed-purpose main() method for testing.



Is that complete enough?

Context

StackExchange Code Review Q#32954, answer score: 7

Revisions (0)

No revisions yet.