Fast Power
2016-08-18 04:57
302 查看
Calculate the an % b where a, b and n are all 32bit integers.
Analyse: divide and conquer. Be aware of overflow.
Runtime: 12ms
Analyse: divide and conquer. Be aware of overflow.
Runtime: 12ms
class Solution { public: /* * @param a, b, n: 32bit integers * @return: An integer */ int fastPower(int a, int b, int n) { // write your code here if (!a || b == 1 || n < 0) return 0; if (!n && b != 1) return 1; if (n == 1) return a % b; long temp1 = fastPower(a, b, n / 2); long temp = temp1 * temp1 % b; if (n % 2) temp *= a % b; return (int)(temp % b); } };
相关文章推荐
- Print Numbers by Recursion
- MyBatis Generator
- Install and config Redis on Mac OS X via Homebrew
- LeetCode--No.219--Contains Duplicate II--有个地方不太懂
- 【BLE】CC2541之Large OAD
- 文章末页页数
- Ericsson open-sources OpenWebRTC and Bowser for iOS; Intel releases IoT developer kit
- MySQL 体系结构和存储引擎
- seajs 2.x _ 非模块化的调用方式
- struts2 动态Action
- 五险一金
- struts2 入门程序
- Imagination的ClearCall VoIP应用现可支持Cavium的OCTEON III多核处理器
- LeetCode--No.88--Merge Sorted Array
- python--字符编码
- H5常用代码:适配方案4
- seajs 2.x _ 模块的相互引用
- Error inflating class fragment 解决方案
- 23. Merge k Sorted Lists
- HDU 5847 Different Sums (构造+数学+打表)