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 }

 

转载于:https://www.cnblogs.com/Deribs4/p/7216625.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值