class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
return ((num-1)%9)+1 if num else 0
#除开0后还需要输出的范围[1,9],而对9取余结果范围[0,8],故需要+1
class Solution(object):
def largestPalindrome(self, n):
"""
:type n: int
:rtype: int
"""
a, b = 1, 9
while n > a*b:
n = n - a*b
a, b = a+1, b*10
m = n//a + 10**(a-1) -1 #a为位数
return (m+1)//10**(a-n%a)%10 if n%a else m%10
f(a, mn) = a\^(m\*10)\*a\^n % k = f(a,m\*10) \* f(a,n) % k,而f(a,m*10) = (a^m)^10 % k = f(a^m, 10)
通过观察发现需要需要编写一个计算f(i,j)的函数poww(i,j),其中j-0,10,
当j=0时,结果为1;
当j=1时,结果为a^k;
当j-2,10时,结果为 f(j) = f(j-1) \* f(1) % k 需要循环j-1次
python复制代码
class Solution(object):
def superPow(self, a, b):
"""
:type a: int
:type b: List[int]
:rtype: int
"""
if a == 1: return 1 #直接结束
if len(b)==1: return self.poww(a,b[-1]) #不需要拆分b
else:
out1 = self.superPow(a,b[-1:]) #fn
out2 = self.poww(self.superPow(a,b[:-1]),10) #fm*10
return (out1 * out2) % 1337
def poww(self, a, b): #计算a^b % k
if b==0: return 1
elif b==1:return a % 1337
else:
out = f1 = a % 1337
for _ in range(b-1): out = (out * f1) % 1337 #b-1次循环
return out
#测试用时较长,内存占用较多