令n为任何以2为底的幂,即2 n 。我们给定数字n,我们的任务是找出数字2 n中包含的位数。
例子:
Input : n = 5
Output : 2
Explanation : 2n = 32, which has only
2 digits.
Input : n = 10
Output : 4
Explanation : 2n = 1024, which has only
4 digits.
我们可以使用对数写出2 n :
2 n = 10 nlog 10 2
现在假设x = nlog 10 2,
因此,2 n = 10 x
同样,我们都知道数字10 n将具有(n + 1)个数字。因此,10 x将具有(x + 1)个数字。
或者,我们可以说2 n将具有(x + 1)个数字,即2 n = 10 x 。
因此,2 n中的位数=(nlog 10 2)+1
下面是上述想法的实现:
C++
// CPP program to find number of digits
// in 2^n
#include
using namespace std;
// Function to find number of digits
// in 2^n
int countDigits(int n)
{
return (n * log10(2) + 1);
}
// Driver code
int main()
{
int n = 5;
cout << countDigits(n) << endl;
return 0;
}
Java
// Java program to find number
// of digits in 2^n
import java.util.*;
class Gfg
{
// Function to find number of digits
// in 2^n
static int countDigits(int n)
{
return (int)(n * Math.log10(2) + 1);
}
// Driver Code
public static void main(String args[])
{
int n = 5;
System.out.println(countDigits(n));
}
}
// This code is contributed by Niraj_Pandey.
Python3
# Python3 program to find
# number of digits in 2^n
import math
# Function to find number
# of digits in 2^n
def countDigits(n):
return int(n * math.log10(2) + 1);
# Driver code
n = 5;
print(countDigits(n));
# This code is contributed
# by mits
C#
// C# program to find number
// of digits in 2^n
using System;
class GFG
{
// Function to find
// number of digits in 2^n
static int countDigits(int n)
{
return (int)(n * Math.Log10(2) + 1);
}
// Driver code
static void Main()
{
int n = 5;
Console.Write(countDigits(n));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
PHP
Javascript
输出:
2
时间复杂度: O(n)
辅助空间: O(1)