lintcode(140)快速幂
来源:互联网 发布:网络机顶盒和网络电视 编辑:程序博客网 时间:2024/05/18 00:35
Description:
计算an % b,其中a,b和n都是32位的整数。
Explanation:
例如 231 % 3 = 2
例如 1001000 % 1000 = 0
Solution:
每次对n/2,减少一半的计算量,直至n=0或n=1;每次返回余数,平方再求余。注意n是奇数偶数,如果是技术,要补回舍去的1次幂,即乘以a%b,再求余。
class Solution { /* * @param a, b, n: 32bit integers * @return: An integer */ public 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; } long remainder = (long)fastPower(a , b , n/2); remainder = remainder * remainder % b; if(n%2 == 1){ remainder = remainder * (a%b) % b; } return (int)remainder; }};
阅读全文
0 0
- LintCode 140-快速幂
- lintcode(140)快速幂
- LintCode-剑指Offer-(140)快速幂
- LintCode-快速幂
- Lintcode快速幂
- lintcode-快速幂-125
- LintCode 快速幂
- Lintcode 快速幂
- lintcode之快速幂
- lintcode ----快速幂
- LintCode :快速幂
- 快速幂-LintCode
- [LintCode]140.快速幂
- 快速幂—LintCode
- [LintCode] 快速幂 Fast Power
- lintcode刷题——快速幂
- LintCode
- lintcode--
- 快速排序
- 【bzoj3505】[Cqoi2014]数三角形
- Spring-Ioc
- mysql表分区
- 在 System.Threading.ThreadAbortException 中出现的“mscorlib.dll”类型的异常
- lintcode(140)快速幂
- TPshop 2.05开源商城同步官方首发
- Redis使用详细教程
- JaveScript SetInterval 与setTimeout使用方法详解
- Codeforce Round #416
- java类和对象初始化
- 《程序员的呐喊》读书笔记(下)
- Linux 64位下Oracle 12CR2安装(一)
- myeclipse安装lombok插件