5 Divisiblity不使用%,和/操作者 [英] Divisiblity of 5 without using % and / operator
本文介绍了5 Divisiblity不使用%,和/操作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检查一个数是否整除5,并无须使用%和/运营商。 我想一个最快的算法,对于这个问题。
how to check whether a number is divisible by 5 or not without using % and / operator. I want a quickest algorithm for this problem.
推荐答案
一个很好的出发点是要考虑如何划分可以完成与乘法和位的变化。 这个问题是一个地方看。
A good starting point is to look into how division can be accomplished with multiplication and bit-shifts. This question is one place to look.
在特定的,可以按照连接后在以下策略来打。首先,用乘法和位移除以5:
In particular, you can follow the attached post to hit upon the following strategy. First, "divide by 5" using multiplication and bit-shifts:
int32_t div5(int32_t dividend) {
int64_t invDivisor = 0x33333333;
return 1 + (int32_t) ((invDivisor * dividend) >> 32);
}
然后,把结果乘以5:
Then, take the result and multiply by 5:
int result = div5(dividend) * 5;
然后,结果==分红
,当且仅派息
是整除5。
Then, result == dividend
if and only dividend
is divisible by 5.
if(result == dividend) {
// dividend is divisible by 5
}
else {
// dividend is not divisible by 5
}
这篇关于5 Divisiblity不使用%,和/操作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文