题目描述
请编写一个方法,实现整数的乘法、减法和除法运算(这里的除指整除)。只允许使用加号。
给定两个正整数int a,int b,同时给定一个int type代表运算的类型,1为求a * b,0为求a / b,-1为求a - b。请返回计算的结果,保证数据合法且结果一定在int范围内。
测试样例:
1,2,1
返回:2
解题思路:
a/b,如果a> b,则循环 b+=b,直到b大于a,统计加了几次
import java.util.*;
public class AddSubstitution {
public int calc(int a, int b, int type) {
// write code here
int i = 1;
if (type == 1) {
int temp = a;
while (i < b) {
temp += a;
i++;
}
return temp;
} else if (type == 0) {
if (a < b)
return 0;// 因为是正整数
int temp = b;
while (temp <= a) {
if (temp == a)
return i;
temp += b;
i++;
}
return i-1;
}
else if (type == -1) {
while (i <= b) {
a--;
i++;
}
return a;
}
return -1;
}
}