华为笔试java
第一题 AC
考虑第一个数十进制与十六进制互转
package huawei; import java.util.Scanner; public class p1 { public static void main(String[] args){ Scanner input = new Scanner(System.in); String s = input.next(); int n = hextoten(s); String[] str = new String[n - 1]; for(int i = 0; i < n - 1; i++){ str[i] = input.next(); } int count = 1; StringBuilder sb = new StringBuilder(); for(int i = 0; i < n - 1; i++){ char[] c = str[i].toCharArray(); if(c[0] == 'A'){ sb.append(" 12" + " 34" ); count = count + 2; }else if(c[0] == 'B'){ sb.append(" AB" + " CD"); count = count + 2; }else{ sb.append(" " + c[0]); count ++; } } String countres = tentohex(count); String res = countres + sb.toString(); System.out.println(res); } private static int hextoten(String str){ int res = 0; for(int i = 0; i < str.length(); i++){ res = res * 16; if(str.charAt(i) >= '0' && str.charAt(i) <= '9') { res = res + (str.charAt(i) - '0'); }else{ res = res + (str.charAt(i) - 'A' + 10); } } return res; } private static String tentohex(int num){ char[] map = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; String res = ""; while(num != 0){ int x = num&0xF; res = map[(x)] + res; num = (num >>> 4); } return res; } }
第二题 AC
package huawei; import java.util.Scanner; public class p2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int low = input.nextInt(); int high = input.nextInt(); int one = 0; int ten = 0; for(int i = low; i < high; i++){ if(fun(i) == true){ int num = i; one += num % 10; num /= 10; ten += num % 10; } } int res = Math.min(one, ten); System.out.println(res); } private static boolean fun(int n){ for(int i = 2; i < n; i++){ if(n % i == 0) return false; } return true; } }第三题 用HashSet,暴力出来只有80
package huawei; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class p3 { public static void main(String[] args) { Scanner input = new Scanner(System.in); String str1 = input.nextLine(); int m = input.nextInt(); input.nextLine(); HashSet<String> set = new HashSet<String>(); set.add(str1); ArrayList<String> list = new ArrayList<>(); for(int i = 0; i < m; i++){ String strtemp = input.nextLine(); list.add(strtemp); for(String str : set){ if(strtemp.contains(str)){ String[] array = strtemp.split(","); for(int j = 0; j < array.length; j++){ set.add(array[j]); } break; } } } for(int t = 0; t < m; t++) { for (int i = 0; i < m; i++) { String strtemp = list.get(i); for (String str : set) { if (strtemp.contains(str)) { String[] array = strtemp.split(","); for (int j = 0; j < array.length; j++) { set.add(array[j]); } break; } } } } int res = set.size(); System.out.println(res); } }