在 C 位中,乘以 3 并除以 16 [英] In C bits, multiply by 3 and divide by 16

查看:25
本文介绍了在 C 位中,乘以 3 并除以 16的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个朋友遇到了这些谜题,而我一直在想这个.问题来了,给你一个数字,你想返回这个数字乘以 3,然后除以 16,四舍五入为 0.应该很容易.捕获?您只能使用 !〜&^ |+ <<>> 运算符和其中只有 12 个的组合.

A buddy of mine had these puzzles and this is one that is eluding me. Here is the problem, you are given a number and you want to return that number times 3 and divided by 16 rounding towards 0. Should be easy. The catch? You can only use the ! ~ & ^ | + << >> operators and of them only a combination of 12.

int mult(int x){
    //some code here...
return y;
}

我的尝试是:

    int hold = x + x + x;
    int hold1 = 8;
    hold1 = hold1 & hold;
    hold1 = hold1 >> 3;
    hold = hold >> 4;
    hold = hold + hold1;
    return hold;

但这似乎不起作用.我认为我有丢失位的问题,但我似乎无法想出保存它们的方法.换个角度就好了.顺便说一句,你也只能使用 int 类型的变量,不能使用循环,可以使用 if 语句或函数调用.

But that doesn't seem to be working. I think I have a problem of losing bits but I can't seem to come up with a way of saving them. Another perspective would be nice. Just to add, you also can only use variables of type int and no loops, if statements or function calls may be used.

现在我的号码是 0xfffffff.它应该返回 0x2ffffff,但它返回的是 0x3000000.

Right now I have the number 0xfffffff. It is supposed to return 0x2ffffff but it is returning 0x3000000.

推荐答案

对于这个问题,您需要担心除法之前丢失的位(显然).本质上,如果它是负数,那么您想在乘以 3 后加上 15.一个简单的 if 语句(使用您的运算符)就足够了.

For this question you need to worry about the lost bits before your division (obviously). Essentially, if it is negative then you want to add 15 after you multiply by 3. A simple if statement (using your operators) should suffice.

我不会给你代码,但一步一步看起来像,

I am not going to give you the code but a step by step would look like,

x = x*3

获取符号并将其存储在变量 foo 中.

get the sign and store it in variable foo.

让另一个变量保持 x + 15;

have another variable hold x + 15;

设置一个 if 语句,如果 x 为负,则使用加 15,如果不是,则使用常规数字(我们在上面所做的乘以 3).

Set up an if statement so that if x is negative it uses that added 15 and if not then it uses the regular number (times 3 which we did above).

然后除以 16,你已经展示了你知道如何做.祝你好运!

Then divide by 16 which you already showed you know how to do. Good luck!

这篇关于在 C 位中,乘以 3 并除以 16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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