C++ | Math | Clear Code with Explanation
1015. Smallest Integer Divisible by K\n\nAn intuitive solution is to check the number one by one.\ncpp\nint n = 1, len = 1;\nwhile (n % k != 0)\n    len += 1, n
**1015. Smallest Integer Divisible by K**\n\nAn intuitive solution is to check the number one by one.\n```cpp\nint n = 1, len = 1;\nwhile (n % k != 0)\n    len += 1, n = n * 10 + 1;\nreturn len\n```\n\nHowever, there are two problems in this intuitive solution:\n+ `n` may overflow `INTMAX`, hence we should use the remainer of `n % k` as the next value to be checked.\n+ such `n` which satisfy `n % k == 0` may not exist.\n\nTo fix 1st issue:\n```cpp\nint n = 1, len = 1;\nwhile (n % k != 0)\n    len += 1, n = (n * 10 + 1) % k;\nreturn len\n```\n\nAnd based on this code, we can infer that `n` may have `k` different values at most.\n\nTo fix 2nd issue, we can try to check each possible value of `n` (which means we would try `k` times at most.)\n\nSince `n = (n * 10 + 1) % k`, it\'s sure that the remainer is different after each step of loop.\n\n```cpp\nclass Solution {\npublic:\n    int smallestRepunitDivByK(int k) {\n        if ((k & 1) == 0) return -1;\n        int len = 1, n = 1;\n        for (int i = 1; i <= k; ++i)\n        {\n            if (n % k == 0) return len;\n            n = (n * 10 + 1) % k, len += 1;\n        }\n        return -1;\n    }\n};\n```\n
['C']