阿里巴巴笔试
- 将一个16进制的数,统计它的1个个数
思路:遍历字符串,将每一个字符进行判断,每一个字符可以具体表示有多少个1,最后累加即可
public static void main(String[] args) { int sum = 0; Scanner sc = new Scanner(System.in); String str_one = sc.nextLine(); for (int i = 2; i < str_one.length(); i++) { sum += getNum(str_one.charAt(i)); } System.out.println(sum); } public static int getNum(char ch) { switch (ch) { case '0': return 0; case '1': case '2': case '4': case '8': return 1; case '3': case '5': case '6': case '9': case 'a': case 'c': return 2; case '7': case 'b': case 'd': case 'e': return 3; case 'f': return 4; default: return -1; } }
- 给一个只含0 和1 的n * m数组,0代表灯光,1代表人,如果当前位置为0,会向上下左右发射光源,如果遇到1,则得一分,返回总共的分数
思路:对于二维数组中的0,进行上下左右四个方向遍历,一旦遇到1,ans++,且中断当前方向的遍历。四个方向便利完成之后,继续寻找下一个0.
package alibaba; import java.util.Scanner; /** * @author lhb * @date 2022/3/14 */ public class Main03 { static int n, m, ret = 0; static int[][] arr; static int dfs(int[][] arr, int i, int j) { int ans = 0; for (int id = i; id < n; id++) { if (arr[id][j] == 1) { ans++; break; } } for (int id = i; id >= 0; id--) { if (arr[id][j] == 1) { ans++; break; } } for (int id = j; id < m; id++) { if (arr[i][id] == 1) { ans++; break; } } for (int id = j; id >= 0; id--) { if (arr[i][id] == 1) { ans++; break; } } return ans; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] s1 = in.nextLine().split(" "); n = Integer.parseInt(s1[0]); m = Integer.parseInt(s1[1]); arr = new int[n][m]; for (int i = 0; i < n; i++) { String[] s2 = in.nextLine().split(" "); for (int j = 0; j < m; j++) { arr[i][j] = Integer.parseInt(s2[j]); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m ;j++) { if (arr[i][j] == 0) { ret += dfs(arr, i, j); } } } System.out.println(ret); } }

浙公网安备 33010602011771号