阿里实习生2021-3-15场笔试题
第一题:翻转数字
给你三个数a,b,c,可以对a或b进行多次翻转,[一次翻转的意思是取一位二进制进行翻转(比如0->1,或者1->0)],现在问你最少需要多少次翻转可以使得翻转后的a|b=c。
这里给一下我的代码吧~
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
*
* @author Soarkey
* @date 2021/3/15
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t = in.nextInt();
while (t-- != 0) {
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int ans = 0;
// 获取二进制位
while (a != 0 || b != 0 || c != 0) {
int i = a & 1;
int j = b & 1;
int k = c & 1;
if ((i | j) != k) {
if (k == 1) {
++ans;
} else { // k == 0
if ((i & j) == 1) {
ans += 2;
} else {
++ans;
}
}
}
a >>= 1;
b >>= 1;
c >>= 1;
}
out.println(ans);
}
in.close();
out.close();
}
}
第二题:蜡烛
现在有一根蜡烛长 n 厘米,从一端点火,然后对n-1个位置进行随机切割,将蜡烛分为两段,x和n-x,待较短的一段燃尽后(这里假设x段比较短,较短的一段燃尽后,两段蜡烛长度就变成了 0 和 n-x-x 了,注意这里两段蜡烛是同时在燃烧!!),再对剩余的蜡烛(即n-x-x段)进行下一轮切割。【注意只能切割两次,这里我看漏题了!qswl!】
一种切割方案会产生一个蜡烛燃烧的时间t,现在要求得所有切割方案下蜡烛燃烧时间的期望值。
画了个粗略的草图,如下:
这道题我只想出了dfs的方法,但是超时了,贴在下面供大家参考,如果有同学有更棒的idea,欢迎评论区讨论,大家一起学习!
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* 蜡烛
*
* @author Soarkey
* @date 2021/3/15
*/
public class Main {
private static float ans = 0.0f;
private static int k = 0;
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
while (in.hasNextInt()) {
int n = in.nextInt();
ans = 0.0f;
k = 0;
dfs(n, 0);
out.format("%.4f\n", ans / k);
}
in.close();
out.close();
}
public static void dfs(int len, int cur) {
if (len == 1 || len == 2) {
++k;
ans += (cur + 1);
return;
}
for(int i=1; i<len; ++i){
int a = Math.max(i, len - i);
int b = Math.min(i, len - i);
int nextLen = a - b;
dfs(nextLen, cur + b);
}
}
}


海康威视公司福利 1261人发布