Link:

  https://www.hackerrank.com/challenges/kaprekar-numbers

 1 from __future__ import print_function
 2 
 3 
 4 def find_kaprekar(num):
 5 
 6     num_square = str(num ** 2)
 7 
 8     if len(num_square) == 1:
 9         if num == 1:
10             print (num, end = ' ')
11             return True
12     elif len(num_square) % 2 == 0:
13         d = len(num_square) / 2
14         if num == int(num_square[0:d]) + int(num_square[d:2*d]):
15             print (num, end = ' ')
16             return True
17     else:
18         d = len(num_square) // 2 
19         if num == int(num_square[0:d]) + int(num_square[d:(2*d+1)]):
20             print (num, end = ' ')
21             return True
22 
23 
24 
25 
26 def main():
27 
28     p = int(raw_input())
29     q = int(raw_input())
30 
31     have_kaprekar_num = False
32 
33     for i in xrange(p, q+1):
34         if find_kaprekar(i):
35             have_kaprekar_num = True
36 
37     if have_kaprekar_num == False:
38         print("INVALID RANGE")
39     else:
40         print()
41 
42 main()

 

//其他1

 1 def is_kaprekar(n):
 2     squared = str(n ** 2)
 3     mid = len(squared) - len(str(n))
 4     a = int(squared[mid:]) # 这种写法更简便
 5     b = int(squared[:mid]) if len(squared) > 1 else 0
 6     return a + b == n # 直接返回一个判断式子
 7 
 8 p = int(raw_input())
 9 q = int(raw_input())
10 
11 kaprekars = [str(x) for x in xrange(p, q + 1) if is_kaprekar(x)]
12 print ' '.join(kaprekars) if kaprekars else 'INVALID RANGE' # join函数的使用

 

//其他2

 1 import sys
 2 
 3 p = int(sys.stdin.readline())
 4 q = int(sys.stdin.readline())
 5 
 6 kaprekar = [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4950, 5050, 7272, 7777, 9999, 17344, 22222, 77778, 82656, 95121, 99999] # 更省资源,因为数量不多,所以干脆一次性算出
 7 ans = [str(k) for k in kaprekar if k>=p and k<=q]
 8 if ans:
 9     print ' '.join(ans)
10 else:
11     print 'INVALID RANGE'

 

 posted on 2015-05-18 08:44  sangocare  阅读(231)  评论(0编辑  收藏  举报