乱世@小熊 2012-07-27 19:34 采纳率: 25%
浏览 613
已采纳

将数字除以3,不使用 * ,/ ,+ ,-,% 操作符

How would you divide a number by 3 without using *, /, +, -, %, operators?

The number may be signed or unsigned.

转载于:https://stackoverflow.com/questions/11694546/divide-a-number-by-3-without-using-operators

  • 写回答

30条回答 默认 最新

  • lrony* 2012-08-01 15:16
    关注

    This is a simple function which performs the desired operation. But it requires the + operator, so all you have left to do is to add the values with bit-operators:

    // replaces the + operator
    int add(int x, int y)
    {
        while (x) {
            int t = (x & y) << 1;
            y ^= x;
            x = t;
        }
        return y;
    }
    
    int divideby3(int num)
    {
        int sum = 0;
        while (num > 3) {
            sum = add(num >> 2, sum);
            num = add(num >> 2, num & 3);
        }
        if (num == 3)
            sum = add(sum, 1);
        return sum; 
    }
    

    As Jim commented this works, because:

    • n = 4 * a + b
    • n / 3 = a + (a + b) / 3
    • So sum += a, n = a + b, and iterate

    • When a == 0 (n < 4), sum += floor(n / 3); i.e. 1, if n == 3, else 0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?