forked from sshpark/LeetCode-Kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
372.super-pow.kt
67 lines (63 loc) · 1.24 KB
/
372.super-pow.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* @lc app=leetcode id=372 lang=kotlin
*
* [372] Super Pow
*
* https://leetcode.com/problems/super-pow/description/
*
* algorithms
* Medium (35.86%)
* Likes: 146
* Dislikes: 602
* Total Accepted: 29.8K
* Total Submissions: 83.1K
* Testcase Example: '2\n[3]'
*
* Your task is to calculate a^b mod 1337 where a is a positive integer and b
* is an extremely large positive integer given in the form of an array.
*
* Example 1:
*
*
*
* Input: a = 2, b = [3]
* Output: 8
*
*
*
* Example 2:
*
*
* Input: a = 2, b = [1,0]
* Output: 1024
*
*
*
*/
class Solution {
private fun qpow(a: Long, b: Long): Long {
var ans = 1L
var b = b
var a = a%1337
while (b > 0) {
if (b%2 == 1L) ans = ans*a
a = a*a%1337
b = b.shr(1)
}
return ans
}
/*
* 4^432 = 4^(400+30+2)
* = 4^400 * 4^30 * 4^2
* = (4^100)^4 * (4^10)^3 * (4^1)^2
*/
fun superPow(a: Int, b: IntArray): Int {
var ans = 1L
var cnt = a.toLong()
for (i in b.size-1 downTo 0) {
ans = ans * qpow(cnt, b[i].toLong()) % 1337
cnt = qpow(cnt, 10)
}
return ans.toInt()
}
}