给定一个以十进制为底的数字A ,任务是从底数B的最后一个数字中找到第N个数字
例子:
Input: A = 100, N = 3, B = 4
Output: 2
Explanation:
(100)4 = 1210
3rd digit from last is 2
Input: A = 50, N = 3, B = 5
Output: 2
Explanation:
(50)5 = 200
3rd digit from last is 2
方法:想法是跳过基数B中给定数字的(N-1)个数字,方法是将数字除以B(N – 1)次,然后将当前数字的模数除以B,得到第N个右边的数字。
下面是上述方法的实现:
C++
// C++ Implementation to find Nth digit
// from right in base B
#include
using namespace std;
// Function to compute Nth digit
// from right in base B
int nthDigit(int a, int n, int b)
{
// Skip N-1 Digits in Base B
for (int i = 1; i < n; i++)
a = a / b;
// Nth Digit from right in Base B
return a % b;
}
// Driver Code
int main()
{
int a = 100;
int n = 3;
int b = 4;
cout << nthDigit(a, n, b);
return 0;
}
Java
// Java Implementation to find Nth digit
// from right in base B
import java.util.*;
class GFG
{
// Function to compute Nth digit
// from right in base B
static int nthDigit(int a, int n, int b)
{
// Skip N-1 Digits in Base B
for (int i = 1; i < n; i++)
a = a / b;
// Nth Digit from right in Base B
return a % b;
}
// Driver Code
public static void main(String[] args)
{
int a = 100;
int n = 3;
int b = 4;
System.out.print(nthDigit(a, n, b));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Ptyhon3 Implementation to find Nth digit
# from right in base B
# Function to compute Nth digit
# from right in base B
def nthDigit(a, n, b):
# Skip N-1 Digits in Base B
for i in range(1, n):
a = a // b
# Nth Digit from right in Base B
return a % b
# Driver Code
a = 100
n = 3
b = 4
print(nthDigit(a, n, b))
# This code is contributed by ApurvaRaj
C#
// C# Implementation to find Nth digit
// from right in base B
using System;
class GFG
{
// Function to compute Nth digit
// from right in base B
static int nthDigit(int a, int n, int b)
{
// Skip N-1 Digits in Base B
for (int i = 1; i < n; i++)
a = a / b;
// Nth Digit from right in Base B
return a % b;
}
// Driver Code
public static void Main()
{
int a = 100;
int n = 3;
int b = 4;
Console.Write(nthDigit(a, n, b));
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
2