给一个数n,改变这个数n的某一位或某几位,使得n被7整除,(改变后的数不能以0开头),
要求改变最少的位数。
给定的n最大是990,所以直接将7-990的7的倍数按照位数不同存下来。
直接遍历判断内即可。
#include2 官方解法#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; }
被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; }



