可以将位置值定义为根据其在数字中的位置,用数字中的数字表示的值。这是带有示例的位置值说明:
让我们再举一个例子来说明N = 45876的位置值
问题:
给定正整数N和数字D。任务是找出给定数字N中的数字D的位置值。如果多次出现数字,则找到最小位数。
例子:
Input: N = 3928, D = 3
Output: 3000
Explaination:
Place value of 3 in this number is 3*1000 = 3000
Input: N = 67849, D = 6
Output: 60000
解决方法:
- 从输入数字的右侧找到数字的位置。为了找到位置,将那个数字的mod乘以10,然后检查该数字,然后将该数字除以10。
- 找到数字的位置后,只需将数字乘以10的位置即可。
这是上述方法的实现:
C++
// C++ implementation to find
// place value of a number
#include
using namespace std;
// Function to find place value
int placeValue(int N, int num)
{
int total = 1, value = 0, rem = 0;
while (true)
{
rem = N % 10;
N = N / 10;
if (rem == num)
{
value = total * rem;
break;
}
total = total * 10;
}
return value;
}
// Driver Code
int main()
{
// Digit, which we want
// to find place value.
int D = 5;
// Number from where we
// want to find place value.
int N = 85932;
cout << (placeValue(N, D));
}
// This code is contributed by Ritik Bansal
Java
// Java implementation to find
// place value of a number
import java.util.*;
import java.io.*;
import java.lang.*;
class GFG {
// function to find place value
static int placeValue(int N, int num)
{
int total = 1, value = 0, rem = 0;
while (true) {
rem = N % 10;
N = N / 10;
if (rem == num) {
value = total * rem;
break;
}
total = total * 10;
}
return value;
}
// Driver Code
public static void main(String[] args)
{
// Digit, which we want
// to find place value.
int D = 5;
// Number from where we
// want to find place value.
int N = 85932;
System.out.println(placeValue(N, D));
}
}
Python3
# Python3 implementation to find
# place value of a number
# Function to find place value
def placeValue(N, num):
total = 1
value = 0
rem = 0
while (True):
rem = N % 10
N = N // 10
if (rem == num):
value = total * rem
break
total = total * 10
return value
# Driver Code
# Digit, which we want
# to find place value.
D = 5
# Number from where we
# want to find place value.
N = 85932
print(placeValue(N, D))
# This code is contributed by divyamohan123
C#
// C# implementation to find
// place value of a number
using System;
class GFG{
// function to find place value
static int placeValue(int N, int num)
{
int total = 1, value = 0, rem = 0;
while (true)
{
rem = N % 10;
N = N / 10;
if (rem == num)
{
value = total * rem;
break;
}
total = total * 10;
}
return value;
}
// Driver Code
public static void Main()
{
// Digit, which we want
// to find place value.
int D = 5;
// Number from where we
// want to find place value.
int N = 85932;
Console.Write(placeValue(N, D));
}
}
// This code is contributed by Code_Mech
输出:
5000
时间复杂度: O(log N)
辅助空间: O(1)