1015. Smallest Integer Divisible by K #2462
-
|
Topics: Given a positive integer Return the length of Note: Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to find the smallest number consisting only of digit '1' that is divisible by k. Approach:
Let's implement this solution in PHP: 1015. Smallest Integer Divisible by K <?php
/**
* @param Integer $k
* @return Integer
*/
function smallestRepunitDivByK($k) {
// If k is even or divisible by 5, no solution exists
// because numbers ending with 1 can't be divisible by 2 or 5
if ($k % 2 == 0 || $k % 5 == 0) {
return -1;
}
$remainder = 0;
// Try up to k iterations - if we don't find 0 by then, it doesn't exist
for ($length = 1; $length <= $k; $length++) {
// Build the number: remainder = (remainder * 10 + 1) % k
$remainder = ($remainder * 10 + 1) % $k;
// If remainder becomes 0, we found our answer
if ($remainder == 0) {
return $length;
}
}
return -1;
}
// Test cases
echo smallestRepunitDivByK(1) . "\n"; // Output: 1
echo smallestRepunitDivByK(2) . "\n"; // Output: -1
echo smallestRepunitDivByK(3) . "\n"; // Output: 3
?>Explanation:
Why the loop runs at most k times?
Example walkthrough for k = 3:
This solution runs in O(k) time and O(1) space, which is efficient for the given constraints (k ≤ 10⁵). |
Beta Was this translation helpful? Give feedback.
We need to find the smallest number consisting only of digit '1' that is divisible by k.
Approach:
Let's implement this solution in PHP: 1015. Smallest Integer Divisible by K