京东8.27笔试
第一题:2,3,5 三个素数 任意拼凑组成数字 第n个为?
e.g. 第3个为5; 第12个为55; 第22个为322
import java.util.Scanner public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextInt()){ int n = scanner.nextInt(); int res = solution(n); System.out.println(res); } } private static int solution(int n) { int[] nums = new int[]{2,3,5}; StringBuilder sb = new StringBuilder(""); if (n == 1) return 2; if (n == 2) return 3; if (n == 3) return 5; // 计算有几位数 int sum = 0; int count = 1; while (sum < n){ sum += Math.pow(3,count); count++; } int numOfDigits = count - 1; // 上一位数 比如 3, 12, 39 int previousDigitNum = (int) (sum - Math.pow(3,numOfDigits)); int index = 0; // tmp number of digits int dig = numOfDigits; for (int i = 1; i <= numOfDigits; i++) { // 计算index 就是 每一位 对应 第几个数 while (previousDigitNum < n) { previousDigitNum = (int) (previousDigitNum + Math.pow(3, dig - 1)); index++; } // 多加的减回来 previousDigitNum = (int) (previousDigitNum - Math.pow(3, dig - 1)); // 每位计算 从最高位向下到最低位 dig = dig - 1; if (index == 1) sb.append(nums[0]); if (index == 2) sb.append(nums[1]); if (index == 3) sb.append(nums[2]); //从新归0 index = 0; } return Integer.parseInt(String.valueOf(sb)); } }第二题:
比如一个 三角形
1
2 4 2
3 4 2 1 3
从上面开始 每次只能向左下、垂直向下、右下走
问走到底,最大值为多少? 比如上图最大值为9: 1->4->4
import java.util.Scanner; public class Main { static int res = Integer.MIN_VALUE; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int nums = scanner.nextInt(); int length = 0; for (int i = 1; i <= nums; i++) { length += 2 * i - 1; } int[] array = new int[length]; for (int i = 0; i < length; i++) { array[i] = scanner.nextInt(); } dfs(array,nums,0,0,0); System.out.println(res); } private static void dfs(int[] array, int nums, int step, int index, int value) { int len = array.length; if (step >= nums || index >= len) { if (res < value) res = value; return; } step++; dfs(array, nums, step, index + (2 * step - 1), value + array[index]); dfs(array, nums, step, index + 1+ (2 * step - 1), value+ array[index]); dfs(array, nums, step, index + 2+ (2 * step - 1), value+ array[index]); } }