We have two big number such that out of range of Integers then, how are you add these number.
we solve this problem using string
public class AddTwoNumber {
static int getCarry(int num){
return ((num)>9 && (num)<20?1:(num)>=20?2:0);
}
static int getRemander(int num){
return ((num)>=10?(num)%10:(num));
}
static String AddBigNumber(String num1 , String num2){
String sum="";
// int length=(num1.length()>num2.length()?num1.length():num2.length());
int length1=(num1.length()-1);
int length2=(num2.length()-1);
int carry=0;
int rem=0;
int num=0;
while (length1>=0 && length2>=0) {
int n=num1.charAt(length1)-'0';
int m=num2.charAt(length2)-'0';
num=n+m+carry;
carry=getCarry(num);
rem=getRemander(num);
sum+=rem;
System.out.println("rem="+rem+"carry="+carry+"sum="+sum);
length1--;
length2--;
}
if(!(length1>=0)){
System.out.println("in second ");
while (length2>=0) {
int m=num2.charAt(length2)-'0';
num=m+carry;
carry=getCarry(num);
rem=getRemander(num);
sum+=rem;
length2--;
}
}
if (!(length2>=0)) {
System.out.println("in first ");
while (length1>=0) {
int n=num1.charAt(length1)-'0';
num=n+carry;
carry=getCarry(num);
rem=getRemander(num);
sum+=rem;
length1--;
}
}
if (carry!=0) {
sum+=carry;
}
return sum ;
}
public static void main(String[] args) {
String str=AddBigNumber("12","48");
System.out.println("my sum is");
for (int i = (str.length()-1); i>=0; i--) {
System.out.print(str.charAt(i));
}
}
}
Check a string value is Integer or not in java. (Solution).
Check ia string is hexadecimal number or not (Solution).
Generate Combination in java (Solution).
Generate permutation of string(Solution).
Reverse string in java (Solution).
Find duplicate characters with occurrences in a string(Solution).
Permutation of a number(Soluion).
Split the String in java(Solution).
Convert string into number in java(Solution).
Swap two strings without using any variable(Solution).
Get a number from a string in java(Solution).
Add Two Big Number In Java(Solution).
Expand String(Solution).
Reverse String (Solution).
Related Posts:
Check a string value is Integer or not in java. (Solution).
Check ia string is hexadecimal number or not (Solution).
Generate Combination in java (Solution).
Generate permutation of string(Solution).
Reverse string in java (Solution).
Find duplicate characters with occurrences in a string(Solution).
Permutation of a number(Soluion).
Split the String in java(Solution).
Convert string into number in java(Solution).
Swap two strings without using any variable(Solution).
Get a number from a string in java(Solution).
Add Two Big Number In Java(Solution).
Expand String(Solution).
Reverse String (Solution).
No comments:
Post a Comment