题目链接:https://leetcode-cn.com/problems/smallest-good-base/
思路:
1.先遍历[2, 10]进制是不是满足条件,后面再判断[11, n - 1]
2.假设n转换成x进制等于y, 其中y = 11111…111(长度等于n的长度)
3.二分查找x的值,范围是[11, n - 1]
4.找到对应的x则返回,否则y = y / 10,继续第3步的二分查找
public class Solution {
/// <summary>
/// 判断number转换到baseValue进制是不是全1
/// </summary>
/// <param name="number"></param>
/// <param name="baseValue"></param>
/// <returns></returns>
public bool CheckBase(long number, long baseValue) {
while (0 < number) {
if (1 != number % baseValue) {
break;
}
number = number / baseValue;
}
return (0 == number);
}
/// <summary>
/// 将baseValue进制的number转换成10进制
/// </summary>
/// <param name="number"></param>
/// <param name="baseValue"></param>
/// <returns></returns>
public long To10Base(long number, long baseValue) {
long result = 0;
long mulValue = 1;
while (0 < number) {
result += ((number % 10) * mulValue);
if (long.MaxValue / mulValue < baseValue && 10 <= number) {
//转换超出最大值了
return long.MaxValue;
}
mulValue = mulValue * baseValue;
number = number / 10;
}
return result;
}
public string SmallestGoodBase(string n) {
long number = long.Parse(n);
//先判断是不是10以内的进制
for (int i = 2; i <= 10; i++) {
if (CheckBase(number, i)){
return i.ToString();
}
}
//获取长度为n.Length的全1数字
long max1Value = 0;
long tempNumber = number;
while (0 < tempNumber) {
max1Value = 10 * max1Value + 1;
tempNumber = tempNumber / 10;
}
//再查找(11, number-1]里面的进制
while(11 < max1Value) {
//判断max1Value能不能找到对应的进制
//查找(11, number-1]
long left = 11;
long right = number - 1;
while (left < right) {
long middle = (left + right) >> 1;
long midVaule = To10Base(max1Value, middle);
if (midVaule == number) {
return middle.ToString();
} else if (midVaule < number) {
left = middle + 1;
} else {
right = middle;
}
}
max1Value = max1Value / 10;
}
return (number - 1).ToString();
}
}