题目如下:

Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1.

Return the length of N.  If there is no such N, return -1.

Example 1:

Input: 1
Output: 1
Explanation: The smallest answer is N = 1, which has length 1.

Example 2:

Input: 2
Output: -1
Explanation: There is no such positive integer N divisible by 2.

Example 3:

Input: 3
Output: 3
Explanation: The smallest answer is N = 111, which has length 3.

Note:

  • 1 <= K <= 10^5

解题思路:题目要求找出最小的一个X,使得K*X = 111.....111,一开始我的思路是找出这样的X,例如K=19937,那么X的最后一位一定是3,接下来再计算X的倒数第二位,但是这样会超时,可能是掉入了死循环。其实反过来想想,我们可以111.....111去除以K,判断能否被K整除。首先找出大于或等于K的最小的11...11,然后除以K得到余数,余数后面继续加上最少数量的1使得余数大于K,然后再除以K直到余数为0为止。对于无法被整除的情况,经过若干次操作之后,一定会出现重复的余数,只要用字典记录出现过的余数,如果有重复出现则返回-1。

代码如下:

class Solution(object):
def smallestRepunitDivByK(self, K):
"""
:type K: int
:rtype: int
"""
len_k = len(str(K))
res = len_k
div = '' * (len_k)
if int(div) < K:
div += ''
res += 1
dic_remainder = {}
while True:
remainder = int(div) % K
if remainder == 0:
return res
elif remainder in dic_remainder:
return -1
dic_remainder[remainder] = 1
sr = str(remainder)
div = sr + '' * (len_k - len(sr))
res += (len_k - len(sr))
if int(div) < K:
div += ''
res += 1

最新文章

  1. godep 包管理工具
  2. RecyclerView 滑动检测 (上滑 up)(下滑 down)(顶部 top)(底部 bottom)
  3. Fragment中的onKeyDown事件让Activity处理--处理特殊按键比如移动终端扫描
  4. Makefile &lt;网络转载&gt;
  5. 时间“Thu Aug 14 2014 14:28:06 GMT+0800”的转换
  6. css多栏自适应布局
  7. Qt 常用的功能
  8. Oracle中的rownum和rowid
  9. ServiceStack.Redis之IRedisClient&lt;第三篇&gt;
  10. Tomcat的8009端口AJP的利用
  11. 【剑指offer 面试题34】丑数
  12. setFocusable、setEnabled、setClickable区别
  13. js中的String数据类型
  14. cocos2d-x实战 C++卷 学习笔记--第7章 动作、特效(一)
  15. 【转】unity3d 如何得到当前物体播放的动画
  16. FZU 2092 收集水晶
  17. Error:ivalue require as left operant of assignment
  18. Multi-Database Transaction Demo
  19. Restrict &amp; Cascade
  20. 【nlp】中文分词基础原则及正向最大匹配法、逆向最大匹配法、双向最大匹配法的分析

热门文章

  1. 学习日记14、EF 时间段查询
  2. sqlserver备份和恢复-5
  3. mybatis获取数据库自增id
  4. jinjia2 模板学习
  5. iOS打印各种类型数据
  6. vue项目运行时出现的问题(less、vue poackages version)
  7. &lt; 备考CET6 - 替换词 &gt;
  8. Angular 输入中的禁止特定输入值--Validator 与 Directive 实现
  9. poi小案例
  10. 06 CAS的原理和AQS