Example of addition is given how do i implement subtraction? Thank you, public c
ID: 3661562 • Letter: E
Question
Example of addition is given how do i implement subtraction?
Thank you,
public class Main {
public static void main(String[] args) {
BigInt a = new BigInt("99");
BigInt b = new BigInt("9");
System.out.println(a + " + " + b + " = " + a.add(b));
System.out.println(a + " - " + b + " = " + a.sub(b));
}
}
class BigInt {
public BigInt() {
n = new int[1];
}
public BigInt(String s) {
n = new int[s.length()];
for (int i = 0; i < n.length; ++i) {
n[n.length - i - 1] = s.charAt(i) - '0';
}
}
private BigInt(int[] n) {
this.n = new int[n.length];
for (int i = 0; i < n.length; ++i) {
this.n[i] = n[i];
}
}
public BigInt add(BigInt o) {
int carry = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i) {
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
result[i] = (top + bot + carry) % 10;
carry = (top + bot + carry) / 10;
}
return new BigInt(trim(result));
}
public BigInt sub(BigInt o) {
return null;
}
public String toString() {
String s = "";
for (int i : n) {
s = i + s;
}
return s;
}
private int[] trim(int[] nums) {
int size = nums.length;
for (int i = nums.length - 1; i > 0; --i) {
if (nums[i] != 0) {
break;
}
--size;
}
int[] res = new int[size];
for (int i = 0; i < size; ++i) {
res[i] = nums[i];
}
return res;
}
private int[] n;
}
Explanation / Answer
The subtract funtsion will be coded like this :
public BigInt sub(BigInt o) {
int borrow =10;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i) {
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
if( n[i]> o.n[i])
result[i] = (top - bot ) % 10;
else
result[i]= (top- bottom) +borrow // if upper is small than lower add 10 by borrowing to it
n[i+1]--; //(decreasing the number to the left by 1 if borrow is done)
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.