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();
    }
}

猜你喜欢

转载自blog.csdn.net/Zuo9Yi/article/details/82749364
360