2.80-写出函数threefourths的代码。

接题目:

对于整数参数x,计算3/4x的值,向零舍人。它不会溢出。函
数应该遵循位级整数编码规则。

开始作答 官方答案(已验证)

#include <stdio.h>
#include <assert.h>
#include <limits.h>

/** calculate 3/4x, no overflow, round to zero 
*
* no overflow means divide 4 first, then multiple 3, diffrent from 2.79 here 
*
* rounding to zero is a little complicated. 
* every int x, equals f(first 30 bit number) plus l(last 2 bit number) 
*
* f = x & ~0x3 
* l = x & 0x3 
* x = f + l 
* threeforths(x) = f/4*3 + l*3/4 
*
* f doesn't care about round at all, we just care about rounding from l*3/4 
*
* lm3 = (l << 1) + l 
*
* when x > 0, rounding to zero is easy 
*
* lm3d4 = lm3 >> 2 
*
* when x < 0, rounding to zero acts like divide_power2 in 2.78 
*
* bias = 0x3 // (1 << 2) - 1 
* lm3d4 = (lm3 + bias) >> 2 
*/ 
int threeforths(int x) {
	int is_neg = x & INT_MIN; 
	int f = x & ~0x3; 
	int l = x & 0x3; 
	int fd4 = f >> 2;
	int fd4m3 = (fd4 << 1) + fd4; 
	int lm3 = (l << 1) + l;
	int bias = (1 << 2) - 1; 
	(is_neg && (lm3 += bias));
	int lm3d4 = lm3 >> 2; 
	return fd4m3 + lm3d4; 
}

int main(int argc, char* argv[]) {
	assert(threeforths(8) == 6);
	assert(threeforths(9) == 6); 
	assert(threeforths(10) == 7);
	assert(threeforths(11) == 8);
	assert(threeforths(12) == 9); 
	assert(threeforths(-8) == -6); 
	assert(threeforths(-9) == -6);
	assert(threeforths(-10) == -7); 
	assert(threeforths(-11) == -8);
	assert(threeforths(-12) == -9);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

榆钱不知秋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值