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

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

问题描述

我的一个朋友有这些困惑,这是一个是躲避我。这里的问题是,您将得到一个号码,你想回到那个数字乘以3和除以16对0四舍五入应该是容易的。收获?您只能使用! 〜&安培; ^ | + LT;< >>运营商和他们的仅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类型的变量,没有循环,如果可以用来陈述或函数调用。

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.

推荐答案

有关这个问题,你需要你的师(显然)之前担心丢失位。
从本质上讲,如果是负数,那么你要添加15您3.一个简单的如果语句(使用您的运营商)相乘后应该足够了。

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.

我不打算给你code,但一步步会是什么样子,

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

x = x*3

获得标志并将其存储在变量blarg。

get the sign and store it in variable blarg.

有另一个变量保持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天全站免登陆