Super Pow
来源:互联网 发布:连接虚拟主机mysql 编辑:程序博客网 时间:2024/05/01 01:15
前提知识: ab % k = (a%k)(b%k)%k
对b做二分处理,即 (a^b) % k = (a * a)^(b/2) % k,这样时间复杂度就是logb了
当然还要处理b是奇数的情况,而且b在这道题里是个数组,所以要写一些针对数组的运算函数
class Solution {public:int superPow(int a, vector<int>& b) {int ans = 1;a = a % 1337;while (morethanzero(b)){if (IsOdd(b))ans = (ans * a) % 1337;div(b, 2);a = (a * a) % 1337;}return ans;}void div(vector<int> &x, int y){int tmp = 0;for (int i = 0; i < x.size(); i++){x[i] += tmp * 10;tmp = x[i] % y;x[i] = x[i] / y;}}bool IsOdd(const vector<int> & nums){if (nums.back() & 1)return true;elsereturn false;}bool morethanzero(vector<int> & x) {for (int i = x.size() - 1; i >= 0; i--) {if (x[i] > 0) return true;}return false;}};然而还是超时了,囧,因为每次做除法的时候都要遍历一遍数组,所以时间复杂度实际上是nlogb
最后用了官方discuss里的一份代码,简单解释一下:
a^1234567 % k = (a^1234560 % k) * (a^7 % k) % k = (a^123456 % k)^10 % k * (a^7 % k) % k
写成函数的形式就是:f(a,1234567) = f(a, 1234560) * f(a, 7) % k = f(f(a, 123456),10) * f(a,7)%k
所以用迭代的方法进行计算
class Solution { const int base = 1337; int powmod(int a, int k) //a^k mod 1337 where 0 <= k <= 10 { a %= base; int result = 1; for (int i = 0; i < k; ++i) result = (result * a) % base; return result; }public: int superPow(int a, vector<int>& b) { if (b.empty()) return 1; int last_digit = b.back(); b.pop_back(); return powmod(superPow(a, b), 10) * powmod(a, last_digit) % base; }};
0 0
- Super Pow
- Super Pow
- Super Pow
- Super Pow
- Super Pow
- Pow(x, n) / Super Pow
- leetcode.372. Super Pow
- LeetCode 372 Super Pow
- leetcode372. Super Pow
- LeetCode 372. Super Pow
- 372. Super Pow
- LeetCode Super Pow详解
- 372. Super Pow
- [LEETCODE] 372. super pow
- leetcode Super Pow
- LeetCode--372. Super Pow
- 372. Super Pow
- LeetCode: Super Pow
- 时间类总结
- 更新了CocoaPod后变异出现的问题
- 仿微信.QQ聊天界面
- lua之base64加密和解密算法。
- android开发艺术探索(七)
- Super Pow
- 网络通信组织关系剖析
- 增加 修改,装载状态(父品类)
- Linux必会基本知识
- Spring-quartz定时任务
- Android5.0 广播机制源码分析
- 五年 Android 开发,让我 “刻骨铭心” 的那些坑
- Swift傻傻分不清楚系列(一)常量与变量
- spring-boot-starter-logging logback常用配置之<appender>标签详解