给定一个正整数N的任务是从最后一个(最右边)的5 N找到第三位的值。
例子:
Input : N = 6
Output : 6
Explanation : Value of 56 = 15625.
Input : N = 3
Output : 1
Explanation : Value of 53 = 125.
方法:在转向实际方法之前,下面列出了一些与数论有关的事实:
- 5 3是最小的3位数,是5的幂。
- 由于125 * 5 = 625,因此得出结论:数字的倍数(以125结尾)始终为5总是将625构造为结果的最后三位数。
- 再如625 * 5 = 3125,这得出结论:数的倍数(以625结尾)始终为5总是将125构造为结果的最后三位数。
因此,最终的一般解决方案是:
case 1: if n < 3, answer = 0.
case 2: if n >= 3 and is even , answer = 6.
case 3: if n >= 3 and is odd , answer = 1.
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to find the element
int findThirdDigit(int n)
{
// if n < 3
if (n < 3)
return 0;
// If n is even return 6
// If n is odd return 1
return n & 1 ? 1 : 6;
}
// Driver code
int main()
{
int n = 7;
cout << findThirdDigit(n);
return 0;
}
Java
// Java implementation of the
// above approach
class GFG
{
// Function to find the element
static int findThirdDigit(int n)
{
// if n < 3
if (n < 3)
return 0;
// If n is even return 6
// If n is odd return 1
return (n & 1) > 0 ? 1 : 6;
}
// Driver code
public static void main(String args[])
{
int n = 7;
System.out.println(findThirdDigit(n));
}
}
// This code is contributed
// by Akanksha Rai
Python3
# Python3 implementation of the
# above approach
# Function to find the element
def findThirdDigit(n):
# if n < 3
if n < 3:
return 0
# If n is even return 6
# If n is odd return 1
return 1 if n and 1 else 6
# Driver code
n = 7
print(findThirdDigit(n))
# This code is contributed
# by Shrikant13
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to find the element
static int findThirdDigit(int n)
{
// if n < 3
if (n < 3)
return 0;
// If n is even return 6
// If n is odd return 1
return (n & 1)>0 ? 1 : 6;
}
// Driver code
static void Main()
{
int n = 7;
Console.WriteLine(findThirdDigit(n));
}
}
// This code is contributed by mits
PHP
输出:
1