📌  相关文章
📜  在基数Y中找到数字X的最高有效位

📅  最后修改于: 2021-04-23 17:02:50             🧑  作者: Mango

给定两个正整数XY ,任务是在给定的基数Y中找到X的MSB。
例子:

方法:让任务在以Y = 10为基数的情况下找到X = 1234的第一个数字,因此得到第一个数字= 1:

对于任何其他基数,我们可以用Y替换10。因此,我们可以使用以下公式计算基数Y中数字X的第一位:

下面是上述方法的实现:

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)