ACdream1417-Numbers

Numbers

Time Limit: 2000/1000MS (Java/Others)  Memory Limit: 128000/64000KB (Java/Others)
Problem Description
      Consider numbers from 1 to n.
      You have to find the smallest  lexicographically number among them which is divisible by k.
Input

      Input file contains several test cases. Each test case consists of two integer numbers n and k on a line(1 ≤ n ≤ 1018, 1 ≤ k ≤ n).

      The last test case is followed by a line that contains two zeroes. This line must not be processed.

Output
      For each test case output one integer number — the smallest lexicographically number not exceeding n which is divisible by k.
Sample Input
2000 17
2000 20
2000 22
0 0
Sample Output
1003
100
1012
Hint
多组数据
Source
Andrew Stankevich Contest 22
Manager

题意: 给一个数 n(n<10^18),求出字典序最小的不超过 n 的能够整除 k 的最小值

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>

using namespace std;

#define ll long long

int main()
{
    ll n,k,a[20];
    char str[20][20];
    string s[20];
    while(cin>>n>>k)
    {
        if(!n) break;
        int x1=0,x2=0,cnt=0;
        ll m=k,q=n;
        while(q)
        {
            x1++;
            q/=10;
        }
        while(m)
        {
            x2++;
            m/=10;
        }
        ll p=1;\
        a[cnt++]=k;
        for(int i=1; i<x2; i++)
            p*=10;
        for(int i=x2; i<x1; i++)
        {
            p*=10;
            if(p%k==0) a[cnt++]=p;
            else if(p+k-p%k<=n) a[cnt++]=p+k-p%k;
        }
        for(int i=0; i<cnt; i++)
        {
            int sum=0;
            while(a[i])
            {
                int tmp=a[i]%10;
                str[i][sum++]=tmp+'0';
                a[i]/=10;
            }
            str[i][sum] = '\0';
        }
        for(int i=0; i<cnt; i++)
        {
            int len=strlen(str[i]);
            for(int j=0; j<len/2; j++)
            {
                char ch=str[i][len-j-1];
                str[i][len-j-1]=str[i][j];
                str[i][j]=ch;
            }
        }
        for(int i=0; i<cnt; i++)
            s[i]=str[i];
        sort(s, s+cnt);
        cout<<s[0]<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值