[LeetCode] Smallest Integer Divisible by K

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

解题思路

需要迭代的数字为:1, 11, 111, 1111, 11111, ...,又根据公式
(10 * n + 1) % K = (10 * (n % K) + 1) % K,得出迭代方程为:n = (n * 10 + 1) % K

实现代码

// Runtime: 2 ms, faster than 58.32% of Java online submissions for Smallest Integer Divisible by K.
// Memory Usage: 31.8 MB, less than 100.00% of Java online submissions for Smallest Integer Divisible by K.
class Solution {
    public int smallestRepunitDivByK(int K) {
        for (int i = 1, n = 0; i <= K; i++) {
            n = (n * 10 + 1) % K;
            if (n == 0) {
                return i;
            }
        }
        return -1;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,453评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,516评论 0 13
  • 如果蓝色是忧郁 换个绿色试试?
    亲亲酱2099阅读 231评论 0 1
  • 在多个python版本的情况,又不知道安装目录。 想使用python命令知道一下,python具体的安装路径。 使...
    烊柒阅读 4,782评论 0 2
  • 当今社会,有钱任性。垃圾人多,为什么?无知也,不感恩也。动物尚且知感恩之心,何况人乎。平均主义之恶果,白占便宜,不...
    陇右行思阅读 466评论 3 5