Thursday, July 26, 2018

Add 1 to Big Number

//This given code will add value "1" to a number represented as String to accomodate the huge number (can be 100/1000 digits).


package ssl;
public class AddOneToNumber {
    public static void main(String[] args) {
        System.out.println(getMeAddedValue("9"));
        System.out.println(getMeAddedValue("23"));
        System.out.println(getMeAddedValue("49"));
        System.out.println(getMeAddedValue("99"));
        System.out.println(getMeAddedValue("9999"));        
        System.out.println(getMeAddedValue("789"));
        System.out.println(getMeAddedValue("78999999999999999999999999999999"));
    }
    public static String getMeAddedValue(String str){
        boolean flag=true;
        int zeroCount = 0;
        int i=str.length();
        
        while(flag){
            int num = Integer.parseInt(str.substring(i-1, i));
            if(num+1 < 10) {
                str = str.substring(0, i-1) + (num+1);
                break;
            }
            else{
                i--;
                zeroCount++;
                if(zeroCount==str.length()){
                    str = "1";
                    break;
                }
                    
            }
        }
        if(zeroCount>0){
            for(int k=0; k < zeroCount; k++)
                str=str+"0";
        }
        return str;
    }
}

//Output:
10
24
50
100
10000
790
79000000000000000000000000000000

No comments:

Post a Comment