Guru Ji
asked on
Add and Subtract Elements of two arrays
I don't know how easy or hard this is, but I am so confused and cannot think of it.
I have two arrays in reverse order.
So basically
Array a[]=321 ( ie the number is 123)
Array b[] = 9001 (i.e the number is 1009)
I want Array a[] + Array b[] (means 123 + 1009) = 1132
So I have to make a add method which accepts these two arrays as arguments.
Then I add those two numbers and return the value in string or an array, doesn't matter.
How do I do add and subtract method for this problem. As I have to make sure about the carry digit as if we add 9 and 3 its 12, so 1 is carry or so.
I hope you guys/gals understand my problem and if you have any questions then please let me know
Thanks in advance
I have two arrays in reverse order.
So basically
Array a[]=321 ( ie the number is 123)
Array b[] = 9001 (i.e the number is 1009)
I want Array a[] + Array b[] (means 123 + 1009) = 1132
So I have to make a add method which accepts these two arrays as arguments.
Then I add those two numbers and return the value in string or an array, doesn't matter.
How do I do add and subtract method for this problem. As I have to make sure about the carry digit as if we add 9 and 3 its 12, so 1 is carry or so.
I hope you guys/gals understand my problem and if you have any questions then please let me know
Thanks in advance
You mean you want to return 1132?
Sorry - must be getting tired - i see you do ;-)
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Of course you could arrange things so that you only need one loop, called twice
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
unsigned substraction (a must be >= b) :
int[] substract(int[] a,int[] b)
{
int ml=(b.length>a.length)?b.l ength:a.le ngth; // maximum array length
int[] res=new int[ml];
int c=0; // carry
for (int i=0;i<res.length;i++)
{
res[i]=digit(a,i)-digit(b, i)-c+10; // +10 for %
c=1-(res[i]/10);
res[i]%=10;
}
return res;
}
int[] substract(int[] a,int[] b)
{
int ml=(b.length>a.length)?b.l
int[] res=new int[ml];
int c=0; // carry
for (int i=0;i<res.length;i++)
{
res[i]=digit(a,i)-digit(b,
c=1-(res[i]/10);
res[i]%=10;
}
return res;
}
>>If you mean array of integer value :
The code i already posted will work with an array of int or String
The code i already posted will work with an array of int or String
ASKER
Yes I tried everything
@CEHJ your code works great... Thanks
@Webstorm - Your code is great too, I will use it for subtraction
Will assign points when I will be done
Thanks to everyone
@CEHJ your code works great... Thanks
@Webstorm - Your code is great too, I will use it for subtraction
Will assign points when I will be done
Thanks to everyone
8-)