Saturday, January 30, 2016

Add reg. integer and arbitary long integer

Problem: Add regular integer and arbitrary long integer (which is not fit in regular integer). Let's assume arbitrary long integer is available in a string.


Solution:

public class LongNumSum {
     
    public String sum(String a, String b){
        int maxSize = Math.max(a.length(), b.length());
        int minSize = Math.min(a.length(), b.length());
         
        char[] sumArr = new char[maxSize+1];
        int carry = 0;
        int i=a.length()-1;
        int j=b.length()-1;
        int k=maxSize;
        for(int count=0; count<minSize; i--, j--, count++) {
            int val = a.charAt(i)-'0' + b.charAt(j)-'0' + carry;
            if(val > 9) {
                val = val%10;
                carry = 1;
            }
            else {
                carry = 0;
            }
            sumArr[k--] = (char)('0'+val);         
        }
         
        while(i>=0){
            int val = a.charAt(i)-'0' + carry;
            if(val > 9) {
                val = val%10;
                carry = 1;
            }
            else {
                carry = 0;             
            }
            sumArr[k--] = (char)('0'+val);         
            i--;
        }
         
        while(j>=0){
            int val = b.charAt(j)-'0' + carry;
            if(val > 9) {
                val = val%10;
                carry = 1;
            }
            else {
                carry = 0;             
            }
            sumArr[k--] = (char)('0'+val);         
            j--;
        }
     
        if(carry == 1) {
            sumArr[0] = '1';
        } else {           
            System.arraycopy(sumArr, 1, sumArr, 0, maxSize-1);
        }
        return String.valueOf(sumArr);
    }
     
     
    public String sumLongNums(int regInt, String arbInt){      
        String rIntStr = Integer.toString(regInt);
        String sum = sum(rIntStr, arbInt);     
        return sum;    
    }
     
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
         
        LongNumSum l = new LongNumSum();
        System.out.println(l.sumLongNums(123, "789"));
         
        System.out.println(l.sumLongNums(123, "99999"));
         
        System.out.println(l.sumLongNums(9999, "456"));
         
        System.out.println(l.sumLongNums(123, "23958735786483975938759835873597395"));
 
    }
 
}

No comments:

Post a Comment