Smallest Integer Divisible by K

LeetCode Q 1015 - 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

Solution

Code:

public int smallestRepunitDivByK(int K) {
  if (K % 2 == 0 || K % 5 == 0) return -1;
  
  int res = 0;
  for (int N = 1; N <= K; N++) {
    res = (res * 10 + 1) % K;
    if (res == 0) return N;
  }
  
  return -1;
}

Note using res = res * 10 + 1; if (res % K == 0) is not correct since res may cause Integer Overflow issue! Also this is not as efficient as the above code.


   Reprint policy


《Smallest Integer Divisible by K》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC