执行模运算的其他方法 [英] Other ways of performing modulo operation

查看:164
本文介绍了执行模运算的其他方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前段时间我已经看到了使用位运算符执行模运算的技巧。但是现在我不能以任何方式执行正确的操作。谁知道怎么做?从我记得它比使用%更快。

Some time ago I've seen somewhere a trick to perform modulo operation using bit operators. But now I cannot in any way perform proper operation. Anyone knows how to do it ? From what I remember it was faster than using %.

推荐答案

技巧是二进制 AND 一个值为1.任何奇数必须将第一位设置为1.

The "trick" is to binary AND a value with 1. Any odd number must have the first bit set to 1.

所以

var foo = 7;

if( foo & 1 ) { // true
}

使用按位AND在几乎所有平台/浏览器中都有更好的性能。

Using a bitwise AND has a better performance in almost all platforms / browsers.

for(var loop = 0; loop < 10; loop++) {
    if( loop & 1 ) {
        console.log('I am ', loop, ' and I am odd!');
    }
}

这篇关于执行模运算的其他方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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