程序员面试金典——加法运算替代

题目描述

请编写一个方法,实现整数的乘法、减法和除法运算(这里的除指整除)。只允许使用加号。

给定两个正整数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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值