zoukankan      html  css  js  c++  java
  • Leetcode 483. Smallest Good Base

    For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1.

    Now given a string representing n, you should return the smallest good base of n in string format. 

    Example 1:

    Input: "13"
    Output: "3"
    Explanation: 13 base 3 is 111.

    Example 2:

    Input: "4681"
    Output: "8"
    Explanation: 4681 base 8 is 11111.

    Example 3:

    Input: "1000000000000000000"
    Output: "999999999999999999"
    Explanation: 1000000000000000000 base 999999999999999999 is 11.

    Note:

    1. The range of n is [3, 10^18].
    2. The string representing n is always valid and will not have leading zeros.

    Next challenges: Palindrome Number Best Meeting Point Encode and Decode TinyURL 

    思路:首先完成字符串到数字的转换,然后对于特定的num,当前的最长的其他进制的表示长度是进制为2时的表示长度,就是log2(num)+1(注意:10..0有t个0,那么10..0=2^t)。那么指数i的遍历区间就是[1,log2(num)+1]。对于当前数的当前指数i,可能的base整数取值是num^(1/(i-1))。

    代码:

     1 public class Solution {
     2     public String smallestGoodBase(String n) {
     3         long num = Long.parseLong(n);
     4         int maxIndex = (int) (Math.log(num)/Math.log(2) + 1);
     5         for(int i = maxIndex; i >= 3; i--) {
     6             long base = (long)Math.pow(num, 1.0 / (i - 1)), sum = 1, cur = 1;
     7             for(int j = 1; j < i; j++) {
     8                 sum += (cur *= base);
     9             }
    10             if(sum == num) return String.valueOf(base);
    11             // java中没有无符号数,而且Math.pow(base, i) - 1存在精度问题,例如样例"14919921443713777",结果应该为"496",但是下列语句的结果是"14919921443713776"
    12             // if((long)((Math.pow(base, i) - 1) / (base - 1)) == num) return String.valueOf(base);
    13         }
    14         return String.valueOf(num - 1);
    15     }
    16 }
  • 相关阅读:
    FocusScope学习三: 对FocusScope 的探究与总结
    FocusScope学习二: 很好的理解FocusScope的工作原理
    不同XML之间节点的拷贝
    计算几何DotVector
    计算几何Graham法凸包
    计算几何UVa10652
    线性筛三合一,强大O(n)
    计算几何AngRadVector
    线性筛euler,强大O(n)
    矩阵bzoj1898
  • 原文地址:https://www.cnblogs.com/Deribs4/p/7216625.html
Copyright © 2011-2022 走看看