7.4 Write methods to implement the multiply, subtract, and divide operations for integers. Use only the Add operator.
This problem allows us to multiply addition and division, and specifies that only addition can be used. So let's first look at how to use addition to achieve subtraction, and we know that subtracting a number equals the negative number of that count. So let's write a function that asks for a negative number, and for n, we accumulate N-1, and for-N, we accumulate N 1. So the subtraction is done, we look at multiplication, multiplication can also be regarded as a kind of addition, such as a multiplied by B, is the result of the addition of B A, we finally judge the positive and negative, if the symbol A and b opposite, we call the previous negative function. Finally is division, Division can also be converted to addition, such as a divided by B, then we can first initialize the quotient of 0, and then the quotient plus B and a comparison, if small, the quotient adds one, then compare, and so on until the greater than equals a, the symbol is the last to judge, so we use the addition to achieve multiplication subtraction and division See the code below:
classSolution { Public: intNegateinta) {intres =0, d = a <0?1: -1; while(A! =0) {res+=D; A+=D; } returnRes; } intMinus (intAintb) {returnA +negate (b); } intMultiplyintAintb) {if(A < b)returnMultiply (b, a); intres =0; for(inti =0; I < ABS (b); ++i) {res+=A; } returnB >0?res:negate (RES); } intDivideintAintb) {if(b = =0)returnInt_max; intm = ABS (a), n =ABS (b); intres =0, Product =0; while(Product + N <=m) {product+=N; ++Res; } if(A <0&& B <0) || (A >0&& B >0))returnRes; Else returnnegate (RES); }};
There is a leetcode in the divide of the two number division of the problem, the problem is more complicated the implementation process, but the algorithm is very efficient, you can see.
[Careercup] 7.4 Implement Multiply Subtract and Divide for multiplication subtraction and division