程序员代码面试指南刷题--第七章.不用算术运算符实现整数的加减乘除运算

题目描述
给定两个32位整数a和b。要求不使用算术运算符,分别实现a和b的加减乘除运算。如果给定的a和b执行加减乘除的某些结果本来就会导致数据的溢出,那么你实现的函数不需要对那些结果负责(你的输出和加减乘除溢出的结果保持一致就行)。
输入描述:

输出一行,包含两个整数a和b(a和b均为32位整数)和一个运算符,运算符为“+”,“-”,“*”,""中的一个。(数据保证不会出现除0的情况)

输出描述:

输出一个整数,为上述表达式计算出的结果。

示例1

输入

2 * 4

输出

8

解法一:位运算

除法有些特殊

import java.io.*;
import java.util.*;
public class Main{
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] info = br.readLine().trim().split(" ");
        int a = Integer.parseInt(info[0]);
        int b = Integer.parseInt(info[2]);
        getRes(a,info[1],b);
    }
    public static void getRes(int a,String s,int b){
        int res = 0;
        if(s.equals("+")){
            res = add(a,b);
        }else if(s.equals("-")){
            res = del(a,b);
        }else if(s.equals("*")){
            res = mul(a,b);
        }else{
            res = divide(a,b);
        }
        System.out.println(res);
    }
    public static int add(int a,int b){
        while(b!=0){
            int r = (a&b)<<1;
            a = a^b;
            b = r;
        }
        return a;
    }
    public static int del(int a,int b){
        //就是a+(-b)
        //一个数的相反数就是二进制取反+1
        b = add(~b,1);
        return add(a,b);
    }
    public static int mul(int a,int b){
        int res = 0;
        while(b!=0){
            if((b&1)==1){
                res = add(res,a);
            }
            a <<= 1;
            b >>>= 1;
        }
        return res;
    }
    public static int divide(int a,int b){
        if(b==0){
            throw new RuntimeException("by zero");
        }
        if(a==Integer.MIN_VALUE&&b==Integer.MIN_VALUE){
            return 1;
        }else if(b==Integer.MIN_VALUE){
            return 0;
        }else if(a==Integer.MIN_VALUE){
            int res = div(add(a,1),b);
            return add(res,div(del(a,mul(res,b)),b));
        }else{
            return div(a,b);
        }
    }
    public static int div(int a,int b){
        int x = a<0?add(~a,1):a;
        int y = b<0?add(~b,1):b;
        int res = 0;
        for(int i=31;i>=0;i=del(i,1)){
            if((x>>i)>=y){
                res |= (1<<i);
                x = del(x,y<<i);
            }
        }
        return (a<0)^(b<0)?add(~res,1):res;
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值