除以3的一些不使用*,/,+, - ,%运营商 [英] Divide a number by 3 without using *, /, +, -, % operators

查看:126
本文介绍了除以3的一些不使用*,/,+, - ,%运营商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何划分若干由3而不使用 * / + - ,运营商

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

数目可以带符号。

推荐答案

这是一个<一个href=\"http://web.archive.org/web/20121103111129/http://forums.hscripts.com/viewtopic.php?f=13&t=1358\">simple其中执行所需的operation.But它的功能要求 + 运营商,因此,所有你需要做的就是与位运算符添加值:

This is a simple function which performs the desired operation.But it requires + operator, so all you have to do is to add the values with the 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

  • 那么总和+ = A,N = A + B ,并重复

A == 0(N 4;)之和+ =地板(N / 3); 即1,如果n == 3,否则为0

这篇关于除以3的一些不使用*,/,+, - ,%运营商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆