Numbers
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
Consider numbers from 1 to n.
You have to find the smallest lexicographically number among them which is divisible by k.
-
输入
- Input file contains several test cases. Each test case consists of two integer numbers n and k on a line(1 ≤ n ≤ 10^18, 1 ≤ k ≤ n).The last test case is followed by a line that contains two zeroes. This line must not be processed. 输出
- For each test case output one integer number — the smallest lexicographically number not exceeding n which is divisible by k. 样例输入
-
2000 17 2000 20 2000 22 0 0
样例输出
-
1003 100
1012
-
//找出每种位数中字典序最小且能整除的那个数,最多循环18次。。。 #include <stdio.h> #include <math.h> #include <string.h> int getByteNum(long long n) //获取n的位数 { int cnt = 0; while(n > 0) { n /= 10; cnt++; } return cnt; } int main() { long long n, k, temp; int i, numN, numK; char str[20], tstr[20]; while(scanf("%lld%lld", &n, &k) && (n+k)) { sprintf(str, "%lld", k); //给str初始化 numN = getByteNum(n); numK = getByteNum(k); for(i = numK; i <= numN; i++) //注意界限 { temp = pow(10, i); //枚举所有1 10 100 1000。。。每种位数字典序最小的数 if(temp % k == 0 && temp <= n) //能整除最好, 否则就找距离他最小的且能被整除的数 { sprintf(tstr, "%lld", temp); } else { temp = (temp/k+1)*k; //找到比temp大的第一个数 } sprintf(tstr, "%lld", temp); if(strcmp(str, tstr) > 0 && temp <= n) //strcmp比较字典序, 找出最优解 { strcpy(str, tstr); } } printf("%s\n", str); } return 0; }