9.7 Mathematics and Probability (ii)--to achieve multiplication, subtraction, and division of integers, with only a plus sign allowed

Source: Internet
Author: User
Tags integer division

/**

* Function: The multiplication, subtraction and division of integers are realized. Only the plus sign is allowed.

*/

Subtract public static int minus (int a,int b) {return a+negate (b);} Take anti-/** * idea: The positive number of k, only need to be 1 continuous plus k times, negative k of the inverse, only need to be 1 continuous plus k times. * @param A * @return */public static int negate (int a) {int neg=0;int d=a>0?-1:1;while (a!=0) {neg+=d;a+=d;} return neg;} Multiplication/** * Idea: a multiplied by B, that is a continuous plus B times.  * @param A * @param b * @return */public static int multiply (int a,int b) {if (a<b) return multiply (b,a); int sum=0;for (int I=abs (b); i>0;i--) {sum+=a;} if (b<0) sum=negate (sum); return sum;} Take the absolute value/** * idea: that is negative negation. * @param A * @return */public static int abs (int a) {if (a<0) return negate (a); else return A;} Division/** * Idea: Using the equation a=xb, the B is connected with itself until you get a, you can calculate the value of X. The value of x is the number of times B is added. * Note: If a cannot be divisible by B, for integer division, the result is a downward tradeoff. * @param A * @param b * @return * @throws java.lang.ArithmeticException */public static int divide (int a,int b) throws Jav A.lang.arithmeticexception{if (b==0) {throw new Java.lang.ArithmeticException ("Error");} int Absa=abs (a); int absb=abs (b); int product=0;int X=0;while (PRODUCT+ABSB&LT;=ABSA) {product+=absb;x++;} if (a<0&&b<0| | a>0&AMP;&AMP;B&GT;0) return X;elsereturn negate (x);} 


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

9.7 Mathematics and Probability (ii)--to achieve multiplication, subtraction, and division of integers, with only a plus sign allowed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.