9分,而无需使用除法和乘法运算符 [英] Divide by 9 without using division or multiplication operator

查看:187
本文介绍了9分,而无需使用除法和乘法运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题我试图解决这个问题,但不能得到任何办法。任何指针将AP preciated。

This question I have tried to solve it but couldn't get any way. Any pointers would be appreciated.

在做除法的定期减法的方式是不是这里的意图,利用移动运营商来完成这件事是意图巧妙的方法。

Regular subtraction way of doing division is not the intention here, ingenious way of using shifting operator to get this done is the intention.

推荐答案

下面是一个解决方案,通过黑客的喜悦很大程度上启发真的只使用移位:

Here's a solution heavily inspired by Hacker's Delight that really uses only bit shifts:

def divu9(n):
    q = n - (n >> 3)
    q = q + (q >> 6)
    q = q + (q>>12) + (q>>24); q = q >> 3
    r = n - (((q << 2) << 1) + q)
    return q + ((r + 7) >> 4)
    #return q + (r > 8)

这篇关于9分,而无需使用除法和乘法运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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