栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Educational Codeforces Round 122 (Rated for Div. 2) A. Div. 7

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Educational Codeforces Round 122 (Rated for Div. 2) A. Div. 7

题目描述

给一个数n,改变这个数n的某一位或某几位,使得n被7整除,(改变后的数不能以0开头),
要求改变最少的位数。

1

给定的n最大是990,所以直接将7-990的7的倍数按照位数不同存下来。
直接遍历判断内即可。

#include 
#include 
#include 
#include 

using namespace std;

const int N = 1010;

int cnt;
vector nums[3];

int get_num(int x)
{
    return to_string(x).size();
}
int get_dif(int a, int b)
{
    string sa = to_string(a);
    string sb = to_string(b);
    int dif = 0;
    for(int i = 0; i < sa.size(); i ++)
    {
        if(sa[i] != sb[i]) dif ++;
    }
    return dif;
}
void solve()
{
    int x; cin >> x;
    if(x % 7 == 0)
    {
        cout << x << endl;
        return;
    }
    int num = get_num(x);
    num --;
    int dif = 5, res = -1;
    for(int i = 0; i < nums[num].size(); i ++)
    {
        int another = nums[num][i];
        int cur_dif = get_dif(x, another);
        if(cur_dif < dif)
        {
            dif = cur_dif;
            res = another;
        }
    }
    cout << res << endl;
}

int main()
{
    nums[0].push_back(7);
    for(int i = 14; i <= 99; i += 7) nums[1].push_back(i);
    for(int i = 105; i <= 990; i += 7) nums[2].push_back(i);
    int t; cin >> t;
    while(t --) solve();
    return 0;
}
2 官方解法

被7整除,那么改变最后一位,一定可以找到被7整除的数。

#include 
#include 
#include 
#include 

using namespace std;

const int N = 1010;

void solve()
{
    int x; cin >> x;
    
    if(x % 7 == 0) 
    {
        cout << x << endl;
        return;
    }
    int a = x % 10; // 算出来x的最低位是多少
    x -= a;
    for(int i = 0; i <= 9; i ++)
    {
        int cur = x + i;
        if(cur % 7 == 0)
        {
            cout << cur << endl;
            return;
        }
    }
}

int main()
{
    int t; cin >> t;
    while(t --) solve();
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/739446.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号