📌  相关文章
📜  查找小于或等于N且具有奇数位数的正整数的数量

📅  最后修改于: 2021-05-07 04:47:01             🧑  作者: Mango

给定一个整数N(其中1≤N≤10 5) ,任务是找到小于或等于N且具有奇数位数且不带前导零的正整数。

例子:

天真的方法:1遍历到N,并检查每个数字是否包含奇数位。

高效方法:对于价值观:

  • N <10时,有效数字的计数将为N。
  • N / 10 <10时为9
  • 如果N / 100 <10,9 + N – 99
  • N / 1000 <10时为9 + 900
  • N / 10000 <10时,则为909 + N – 9999
  • 否则为90909

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the number of
// positive integers less than or equal
// to N that have odd number of digits
int odd_digits(int n)
{
    if (n < 10)
        return n;
    else if (n / 10 < 10)
        return 9;
    else if (n / 100 < 10)
        return 9 + n - 99;
    else if (n / 1000 < 10)
        return 9 + 900;
    else if (n / 10000 < 10)
        return 909 + n - 9999;
    else
        return 90909;
}
  
// Driver code
int main()
{
    int n = 893;
  
    cout << odd_digits(n);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG 
{
  
// Function to return the number of
// positive integers less than or equal
// to N that have odd number of digits
static int odd_digits(int n)
{
    if (n < 10)
        return n;
    else if (n / 10 < 10)
        return 9;
    else if (n / 100 < 10)
        return 9 + n - 99;
    else if (n / 1000 < 10)
        return 9 + 900;
    else if (n / 10000 < 10)
        return 909 + n - 9999;
    else
        return 90909;
}
  
// Driver code
public static void main(String []args) 
{
    int n = 893;
  
    System.out.println(odd_digits(n));
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 implementation of the approach 
  
# Function to return the number of 
# positive integers less than or equal 
# to N that have odd number of digits 
def odd_digits(n) :
  
    if (n < 10) :
        return n; 
    elif (n / 10 < 10) :
        return 9; 
    elif (n / 100 < 10) :
        return 9 + n - 99; 
    elif (n / 1000 < 10) :
        return 9 + 900; 
    elif (n / 10000 < 10) : 
        return 909 + n - 9999; 
    else :
        return 90909; 
  
# Driver code 
if __name__ == "__main__" : 
  
    n = 893; 
  
    print(odd_digits(n)); 
  
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
                      
class GFG 
{
  
// Function to return the number of
// positive integers less than or equal
// to N that have odd number of digits
static int odd_digits(int n)
{
    if (n < 10)
        return n;
    else if (n / 10 < 10)
        return 9;
    else if (n / 100 < 10)
        return 9 + n - 99;
    else if (n / 1000 < 10)
        return 9 + 900;
    else if (n / 10000 < 10)
        return 909 + n - 9999;
    else
        return 90909;
}
  
// Driver code
public static void Main(String []args) 
{
    int n = 893;
  
    Console.WriteLine(odd_digits(n));
}
}
  
// This code is contributed by 29AjayKumar


输出:
803