#阿里笔试#
- 研发工程师Java岗笔试题
- 3.19
第一题:给定n(n为偶数)个人,规定每个人可以得到一个a[i]的序号,若抽到的序号是某个数字的平方,则获奖,现有一种修改券,可以使自己抽到的序号增减一,每个人可以使用多张,问最少需要多少张修改券可以使获奖人数为一半。
输入: 4 4 7 12 13
输出 : 2
说明: 该序号数组中,4是2的2次幂,7需要两张修改券,所以至少需要两张
题解Java:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
int num = scanner.nextInt();
int s = help(num);
nums[i] = s;
}
int left, right, tem;
//冒泡排序
for (int j = 0; j < n - 1; j++) {
for (int i = 0; i < n - 1; i++) {
left = nums[i];
right = nums[i + 1];
if (left >= right) {
tem = right;
nums[i + 1] = left;
nums[i] = tem;
}
}
}
System.out.println(Arrays.toString(nums));
int rs = 0;
for (int i = 0; i <= (n / 2) - 1; i++) {
rs = nums[i] + rs;
}
System.out.println(rs);
}
//返回最小奖券数
private static int help(int a) {
int pre = 1, post = 1;
int n = 1;
int mul;
do {
mul = n * n;
if (a == mul) return 0;
pre = n;
post = ++n;
}while ((mul = n*n) <= a);
return Math.min((a - (n-1)*(n-1)),mul - a);
}
}