CF1633A题解

XiaoWang-554 / 2024-01-17 / 原文

Div. 7

题面翻译

给定 \(t\) 组数据。

每组数据给定一个数 \(n\)\(10\le n\le 999\))。

每次操作可以修改 \(n\) 任意一位上的数,将这一位上的数修改为 \(0\sim 9\) 之间的任意数。要求使用最少的修改次数使这个数修改后是 \(7\) 的倍数,并且没有多余的前导 \(0\)。输出修改后的数,如果有多组解,输出任意一种即可。如果已经是 \(7\) 的倍数,那么不需要修改。

题目描述

You are given an integer $ n $ . You have to change the minimum number of digits in it in such a way that the resulting number does not have any leading zeroes and is divisible by $ 7 $ .

If there are multiple ways to do it, print any of them. If the given number is already divisible by $ 7 $ , leave it unchanged.

输入格式

The first line contains one integer $ t $ ( $ 1 \le t \le 990 $ ) — the number of test cases.

Then the test cases follow, each test case consists of one line containing one integer $ n $ ( $ 10 \le n \le 999 $ ).

输出格式

For each test case, print one integer without any leading zeroes — the result of your changes (i. e. the integer that is divisible by $ 7 $ and can be obtained by changing the minimum possible number of digits in $ n $ ).

If there are multiple ways to apply changes, print any resulting number. If the given number is already divisible by $ 7 $ , just print it.

样例

样例输入

3
42
23
377

样例输出

42
28
777

解题思路

题意是让我们改变一个数的某一位数,位数尽可能最低。
因为\(7\)是个位数,因此我们只需要改变一个数的个位,即在\(0-9\)里面选一个数来代替这个数的个位即可。直到这个数能被\(7\)整除为止,如果将\(7\)换为其他个位数也能用这个方法。选数代替个位这个过程我们可以用枚举来完成。

AC代码

#include<iostream>
using namespace std;
int main()
{
	int t, n;
	scanf("%d", &t);
	while (t--) {
		scanf("%d", &n);
		//如果这个数能被7整除,那直接输出它就行
		if (n % 7 == 0)
			printf("%d\n", n);
		else {
			//将n的个位数归零,方便下面枚举替换
			n = n - n % 10;
			//从1开始枚举到9,因为7的倍数里面没有个位为0的情况所以直接不枚举0
			for (int i = 1; i < 10; i++) {
				if ((n + i) % 7 == 0) {
					printf("%d\n", n + i);
					break;
				}
			}
		}
	}
	return 0;
}