给定两个正整数int a,int b,同时给定一个int type代表运算的类型,1为求a * b,0为求a / b,-1为求a - b,但规定只能使用加号,请编写程序返回计算结果,并保证数据合法且结果一定在int范围内。
测试样例:
1,2,1
返回:2
import java.util.*; public class AddSubstitution { public int calc(int a, int b, int type) { int res=0; if(type==1){ a=(int)Math.abs(a); b=(int)Math.abs(b); for(int i=0;i<b;i++){ res+=a; } if((a>0&&b<0)||(a<0&&b>0)){ res=(~res)+1; } } if(type==0){ a=(int)Math.abs(a); b=(int)Math.abs(b); int tmp=a; while(a>=b){ a+=(~b)+1; res++; } if((a>0&&b<0)||(a<0&&b>0)){ res=(~res)+1; } } if(type==-1){ res=a+(~b)+1; } return res; } }
public int calc(int a, int b, int type) {
int result = 0; // 乘 if ( type==1 ) { for ( int i=0; i<b; i++ ){ result += a; } } // 除 else if ( type==0 ) { int i = 0; while ( !(i*b<=a && (i+1)*b>a) ) { i++; } result = i; } // 减 else { result = a + (-b); } return result; }
import java.util.*; public class AddSubstitution { public int calc(int a, int b, int type) { int result = 0; switch (type) { case 1: for (int i = 0; i < b; i++) result += a; break; case -1: result = a + ~b + 1; break; case 0: while (a >= b) { result++; a = a + ~b + 1; } break; } return result; } }