360 2018研發崗秋招筆試第二題
輸入:
第一行n
接下來n行,每行輸入三個數(分別代表進位制數hex、陣列左邊界l、陣列右邊界r)
輸出:n行
每一行輸出,輸入的每一行陣列中每個數轉化為對應的進位制數中 包含hex-1的數的個數最多的陣列中的數。
例子:
輸入:
1 (表示只有一行輸入)
8 1 100(表示8進位制和陣列[1,100])
//將1-100中的各個數字轉換為8進位制,然後計算每個轉換後的8進位制數中包含7(8減去1)的個數,求出包含最多7的進位制數。
輸出:
63(63轉換為8進位制數後,包含7最多)
import java.util.Scanner; import java.util.Stack;
public class Main {
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.valueOf(sc.nextLine()); int hex = 0; int l = 0; int r = 0; int[] result =new int[n]; for (int i = 0; i < n; i++) { String[] temp = sc.nextLine().split(" "); hex = Integer.valueOf(temp[0]); l = Integer.valueOf(temp[1]); r = Integer.valueOf(temp[2]); result[i]= getResult(hex, l, r); } printArray(result); }
public static int getResult(int hex, int l, int r) { Stack<Integer> s = new Stack<>(); int max = 0; int count = 0; int result = 0; int p = 0; String t; for (int i = l; i <= r; i++) { p = i; do { s.push(p % hex); p = p / hex; } while (p != 0); for (Integer a : s) { if (a == hex - 1) count++; } if (count > max) { max = count; result = i; } s.clear(); count = 0; } return result; }
// 列印陣列 public static void printArray(int[] arr) { if (arr == null) { return; } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } System.out.println(); } }