理想笔试 理想汽车笔试 理想汽车秋招 0916
笔试时间:2025年9月16日
往年笔试合集:
第一题
定义一个正整数是四重数,当且仅当其至少有四个数位是相同的。例如:
- 4444 是一个四重数,因为其只有四个数位,且均为4
- 12212212 也是一个四重数,因为其有5个数位是2
现在,给定一个整数n,请你计算距离n最近的四重数。
输入描述
输入一个整数n(1≤n≤10^9),表示给定的整数。
输出描述
输出一个整数,表示距离n最近的四重数。 如果存在多个距离n最近的四重数,请输出最小的那个。
样例输入
1110
样例输出
1111
参考题解
解题思路: 最坏情况下只需要经过1000次就可以找到一个四重数,因此直接暴力枚举。从n开始,逐步扩大搜索范围,检查n-d和n+d是否为四重数,找到时结束。如果距离相同,选择较小的数。
C++:
#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> using namespace std; bool is_quadruple(long long x) { string s = to_string(x); map<char, int> cnt; for (char c : s) { cnt[c]++; } for (auto& p : cnt) { if (p.second >= 4) { return true; } } return false; } int main() { long long n; cin >> n; if (is_quadruple(n)) { cout << n << endl; return 0; } int d = 1; while (true) { long long low = n - d; long long high = n + d; vector<long long> candidates; if (low >= 1 && is_quadruple(low)) { candidates.push_back(low); } if (is_quadruple(high)) { candidates.push_back(high); } if (!candidates.empty()) { long long result = *min_element(candidates.begin(), candidates.end()); cout << result << endl; break; } d++; } return 0; }
Java:
import java.util.*; public class Main { public static boolean isQuadruple(long x) { String s = String.valueOf(x); Map<Character, Integer> cnt = new HashMap<>(); for (char c : s.toCharArray()) { cnt.put(c, cnt.getOrDefault(c, 0) + 1); } for (int count : cnt.values()) { if (count >= 4) { return true; } } return false; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); if (isQuadruple(n)) { System.out.println(n); return; } int d = 1; while (true) { long low = n - d; long high = n + d; List<Long> candidates = new ArrayList<>(); if (low >= 1 && isQuadruple(low)) { candidates.add(low); } if (isQuadruple(high)) { candidates.add(high); } if (!candidates.isEmpty()) { long result = Collections.min(candidates); System.out.println(result); break; } d++; } sc.close(); } }
Python:
import sys from collections import Counter def is_quadruple(x): """ 检查整数 x 是否是四重数。 四重数要求至少有一个数字出现至少四次。 """ s = str(x) cnt = Counter(s) for count in cnt.values(): if count >= 4: return True return False data = sys.stdin.read().split() n = int(data[0]) if is_quadruple(n): print(n) else: d = 1 while True: low = n - d high = n + d candidates = [] if lo
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
2025 春招笔试合集 文章被收录于专栏
2025打怪升级记录,大厂笔试合集 C++, Java, Python等多种语言做法集合指南