1. 程式人生 > >記Google的一道面試題(java) Beautiful Numbers

記Google的一道面試題(java) Beautiful Numbers

Beautiful Numbers
在這裡插入圖片描述

在這裡插入圖片描述

思路:
13->三進位制->111
1 * 1+1 * 3+1 * 3 * 3=13
13%3=1,13/3=4
4%3=1,4/3=1
1%3=1,1/3=0

1.第一種情況:資料範圍比較小
程式碼:

package test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;

public class BeautifulNumber {

  public static void main
(String[] args) { Scanner in = new Scanner( new BufferedReader(new InputStreamReader(System.in))); int cases = in.nextInt(); for (int i = 1; i <= cases; ++i) { long n = in.nextLong(); System.out.println("Case #" + i + ": " + beautiful(n)); } } private
static long beautiful(long n) { for (long radix = 2; radix < n; radix++) { if (isBeautiful(n, radix)) { return radix; } } throw new IllegalStateException("Should not reach here."); } private static boolean isBeautiful(long n, long radix) { while (n > 0
) { if (n % radix != 1) { return false; } n /= radix; } return true; } }

效果圖:
在這裡插入圖片描述

2.求解大資料集
思路:
N->r進位制->1111…(k個)
N=r^(k-1)
+r^(k-2)
+…+r+1

k=64…2

程式碼:

package Test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;

public class BeautifulNumberLarge {

    public static void main(String[] args) {
        Scanner in = new Scanner(
                new BufferedReader(new InputStreamReader(System.in)));
        int cases = in.nextInt();
        for (int i = 1; i <= cases; ++i) {
            long n = in.nextLong();
            System.out.println("Case #" + i + ": "
                    + beautiful(n));
        }
    }

    private static long beautiful(long n) {
        for (int bits = 64; bits >= 2; bits--) {
            long radix = getRadix(n, bits);
            if (radix != -1) {
                return radix;
            }
        }

        throw new IllegalStateException("Should not reach here.");
    }

    private static long getRadix(long n, int bits) {
        long minRadix = 2;
        long maxRadix = n;
        while (minRadix < maxRadix) {
            long m = minRadix + (maxRadix - minRadix) / 2;
            long t = convert(m, bits);
            if (t == n) {
                return m;
            } else if (t < n) {
                minRadix = m + 1;
            } else {
                maxRadix = m;
            }
        }
        return -1;
    }

    private static long convert(long radix, int bits) {
        long component = 1;
        long sum = 0;
        for (int i = 0; i < bits; i++) {
            if (Long.MAX_VALUE - sum < component) {
                sum = Long.MAX_VALUE;
            } else {
                sum += component;
            }

            if (Long.MAX_VALUE / component < radix) {
                component = Long.MAX_VALUE;
            } else {
                component *= radix;
            }
        }
        return sum;
    }
}

在這裡插入圖片描述