zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第七章 位运算 只用位运算不用算术运算实现整数的加减乘除运算

    题目

    只用位运算不用算术运算实现整数的加减乘除运算
    

    java代码

    package com.lizhouwei.chapter7;
    
    /**
     * @Description: 只用位运算不用算术运算实现整数的加减乘除运算
     * @Author: lizhouwei
     * @CreateDate: 2018/4/28 20:40
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter7_3 {
    
        //加法
        public int add(int a, int b) {
            int sum = a;
            while (b != 0) {
                sum = a ^ b;//无相位相加
                b = (a & b) << 1;//只考虑进位
                a = sum;
            }
            return sum;
        }
    
        //减法
        public int sub(int a ,int b){
            return add(a,negNum(b));
        }
    
        //乘法
        public int muti(int a ,int b){
            int res=0;
            while (b!=0){
                if((b&1)!=0){
                    res= add(res, a);
                }
                a=a<<1;
                b = b>>>=1;
            }
            return res;
        }
        //取负数
        public int negNum(int n){
            return ~n+1;
        }
        //测试
        public static void main(String[] args) {
            Chapter7_3 chapter = new Chapter7_3();
            int reslt = chapter.add(4, 5);
            System.out.println("4+5=" + reslt);
              reslt = chapter.sub(4, 5);
            System.out.println("4-5=" + reslt);
            reslt = chapter.muti(4,5);
            System.out.println("4*5=" + reslt);
        }
    }
    

    结果

  • 相关阅读:
    洛谷P1199三国游戏
    Cracking the Coding Interview 6.2
    Cracking the Coding Interview 5.2
    Cracking the Coding Interview 5.7
    洗牌算法
    字符串排列组合问题
    指针作为形参
    KMP算法代码
    搜索二叉树
    面试题集锦
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8969688.html
Copyright © 2011-2022 走看看