elliott.david 2012-07-27 19:34 采纳率: 25%
浏览 339
已采纳

在不使用 * ,/ ,+ ,-,% 操作符的情况下,将一个数除以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条回答 默认 最新

  • 关注

    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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算