#140 Fast Power
来源:互联网 发布:js tip 提示框 样式 编辑:程序博客网 时间:2024/04/30 02:39
题目思路:
Calculate the an % b where a, b and n are all 32bit integers.
Example
For 231 % 3 = 2
For 1001000 % 1000 = 0
Challenge
题目思路:O(logn)
题目要求用O(logn),那么就用二分法呗。每次recursion把n二分再二分。但是要注意到n可能为奇数,如果n为odd,那么n = n / 2 * 2 + 1.
Mycode(AC = 16ms):
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 (n == 0) { return 1 % b; } else if (n == 1) { return a % b; } else { // get result of n / 2 long long half_pow = fastPower(a, b, n / 2); // get possible result of n / 2 * 2 long long tmp = (half_pow * half_pow) % b; // if n is odd, then result is n / 2 * 2 + 1 if (n % 2 == 1) { return (tmp * a) % b; } else { return tmp % b; } } }};
0 0
- #140 Fast Power
- [刷题]Fast Power
- lintcode: Fast Power
- *[Lintcode]Fast Power
- Fast Power 解题报告
- LintCode 150 : Fast Power
- Fast Power--lintcode
- 递归----Fast Power Show result
- [LintCode] 快速幂 Fast Power
- Lintcode140 Fast Power solution 题解
- 快速幂(Fast Power)
- fast power关于取模运算
- 02分治算法-02fast-power
- 140.Fast Power-快速幂(中等题)
- fast
- FAST
- fast
- power
- <%@include%> 和 <jsp:include> 的区别
- MYSQL前缀索引
- 错误Resources$NotFoundException: Resource ID #0x7f080004
- 【Leetcode】之Construct Binary Tree from Preorder and Inorder Traversal
- HTML5-布局篇( 总结 )
- #140 Fast Power
- My First Blog
- Linux学习笔记
- 调整数组使奇数全部都位于偶数前面。
- Android恢复出厂设置源码分析,基于Android 6.0
- HDU 2680 Choose the best route(最短路,反向)
- acm一些基础小知识
- (c#)AutoCAD二次开发,[CommandMethod("XXXXX")]未能找到类型或命名空间名
- 上下机---机房收费系统