给定两个正整数X和Y ,任务是在给定的基数Y中找到X的MSB。
例子:
Input: X = 55, Y = 3
Output: 2
Explanation:
55 is 2001 in base 3 with first digit as 2.
Input: X = 123, Y = 10
Output: 1
Explanation:
123 is 123 in base 10 with first digit 1.
方法:让任务在以Y = 10为基数的情况下找到X = 1234的第一个数字,因此得到第一个数字= 1:
Divide 1234 by 1000
= X / 103
= X / 10Number of Digits in X – 1
= X / 10log(X) / log(10) (which is for base 10)
对于任何其他基数,我们可以用Y替换10。因此,我们可以使用以下公式计算基数Y中数字X的第一位:
X / Y(log(X)/log(Y))
下面是上述方法的实现:
C++
// C++ Program to find the
// first digit of X in base Y
#include
using namespace std;
// Function to find the first
// digit of X in base Y
void first_digit(int x, int y)
{
// calculating number of digits of
// x in base y
int length = log(x) / log(y) + 1;
// finding first digit of x in base y
int first_digit = x / pow(y, length - 1);
cout << first_digit;
}
// Driver code
int main()
{
int X = 55, Y = 3;
first_digit(X, Y);
return 0;
}
Java
// Java Program to find the
// first digit of X in base Y
import java.util.*;
class GFG{
// Function to find the first
// digit of X in base Y
static void first_digit(int x, int y)
{
// calculating number of digits of
// x in base y
int length = (int)(Math.log(x) /
Math.log(y) + 1);
// finding first digit of x in base y
int first_digit = (int)(x / Math.pow(y,
length - 1));
System.out.println(first_digit);
}
// Driver code
public static void main(String args[])
{
int X = 55, Y = 3;
first_digit(X, Y);
}
}
// This code is contributed by AbhiThakur
Python3
# Python3 program to find the
# first digit of X in base Y
import math
# Function to find the first
# digit of X in base Y
def first_digit(x, y):
# Calculating number of digits of
# x in base y
length = int (math.log(x) /
math.log(y) + 1)
# Finding first digit of x in base y
first_digit = x / math.pow(y, length - 1)
print(int(first_digit))
# Driver code
X = 55
Y = 3
first_digit(X, Y)
# This code is contributed by ishayadav181
C#
// C# Program to find the
// first digit of X in base Y
using System;
class GFG{
// Function to find the first
// digit of X in base Y
static void first_digit(int x, int y)
{
// calculating number of digits of
// x in base y
int length = (int)(Math.Log(x) /
Math.Log(y) + 1);
// finding first digit of x in base y
int first_digit = (int)(x / Math.Pow(y,
length - 1));
Console.Write(first_digit);
}
// Driver code
public static void Main()
{
int X = 55, Y = 3;
first_digit(X, Y);
}
}
// This code is contributed by Akanksha_Rai
Javascript
输出:
2
时间复杂度: O(1)
辅助空间: O(1)