[Lintcode]140. Fast Power
发布时间:2020-12-14 04:25:18 所属栏目:大数据 来源:网络整理
导读:140. Fast Power 本题难度: Medium Topic: Bit Manipulation Description Calculate the a^n % b where a,b and n are all 32bit positive integers. Example For 231 % 3 = 2 For 1001000 % 1000 = 0 Challenge O(logn) 我的代码 class Solution: """ @para
140. Fast Power
DescriptionCalculate the a^n % b where a,b and n are all 32bit positive integers. Example For 1001000 % 1000 = 0 Challenge 我的代码class Solution: """ @param a: A 32bit integer @param b: A 32bit integer @param n: A 32bit integer @return: An integer """ def fastPower(self,a,b,n): # write your code here if n == 0: return 1%b res = 1 containt = a%b while(n>=1): if n%2 == 1: res = (res*containt)%b containt = (containt*containt)%b n = n//2 return res 思路参考了一下https://www.jiuzhang.com/solution/fast-power/#tag-highlight-lang-python的思路。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |