首页 > 试题广场 >

加法运算替代

[编程题]加法运算替代
  • 热度指数:9378 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定两个正整数int a,int b,同时给定一个int type代表运算的类型,1为求a * b,0为求a / b,-1为求a - b,但规定只能使用加号,请编写程序返回计算结果,并保证数据合法且结果一定在int范围内。

测试样例:
1,2,1
返回:2
投机取消,莫过如此!
发表于 2018-09-10 09:53:32 回复(0)
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;
    }
}

发表于 2017-04-17 18:44:04 回复(0)
  1. 乘法:a*b即为b个a相加;
  2. 减法:a+(-b)
  3. 除法:商需要挨个尝试 从0开始,比较ib是否大于等a,并且(i+1)b是否小于a。
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;
}

发表于 2017-03-31 20:01:57 回复(1)
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;
    }
}

发表于 2016-09-08 02:57:12 回复(0)