Numbers

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值