📌  相关文章
📜  删除由数字9组成的所有数字后的第N个自然数

📅  最后修改于: 2021-04-17 15:05:18             🧑  作者: Mango

给定正整数N ,任务是在除去所有包含数字9的自然数后找到第N自然数。

例子:

天真的方法:解决上述问题的最简单方法是迭代到N,并排除所有小于N且包含数字9的数字最后,打印获得的N自然数。
时间复杂度: O(N)
辅助空间: O(1)

高效的方法:可以基于以下观察来优化上述方法:

请按照以下步骤解决问题:

  • 初始化两个变量,例如res = 0p = 1 将数字存储在基数9中并存储数字的位置。
  • N大于0时进行迭代并执行以下操作:
    • 更新资源作为解析度= RES + P *(N%9)。
    • N除以9,然后将p除以10。
  • 完成上述步骤后,打印res的值。

下面是上述方法的实现:

C++
// C++ implementataion of above approach
 
#include 
using namespace std;
 
// Function to find Nth number in base 9
long long findNthNumber(long long N)
{
    // Stores the Nth number
    long long result = 0;
 
    long long p = 1;
 
    // Iterate while N is
    // greater than 0
    while (N > 0) {
 
        // Update result
        result += (p * (N % 9));
 
        // Divide N by 9
        N = N / 9;
 
        // Multiply p by 10
        p = p * 10;
    }
    // Return result
    return result;
}
 
// Driver Code
int main()
{
    int N = 9;
    cout << findNthNumber(N);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to find Nth number in base 9
  static long findNthNumber(long N)
  {
 
    // Stores the Nth number
    long result = 0;
 
    long p = 1;
 
    // Iterate while N is
    // greater than 0
    while (N > 0) {
 
      // Update result
      result += (p * (N % 9));
 
      // Divide N by 9
      N = N / 9;
 
      // Multiply p by 10
      p = p * 10;
    }
 
    // Return result
    return result;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int N = 9;
    System.out.print(findNthNumber(N));
  }
}
 
// This code is contributed by splevel62.


Python3
# Python 3 implementataion of above approach
 
# Function to find Nth number in base 9
def findNthNumber(N):
   
    # Stores the Nth number
    result = 0
    p = 1
 
    # Iterate while N is
    # greater than 0
    while (N > 0):
       
        # Update result
        result += (p * (N % 9))
 
        # Divide N by 9
        N = N // 9
 
        # Multiply p by 10
        p = p * 10
    # Return result
    return result
 
# Driver Code
if __name__ == '__main__':
    N = 9
    print(findNthNumber(N))
     
    # This code is contributed by bgangwar59.


C#
// C# implementataion of above approach
using System;
class GFG
{
  // Function to find Nth number in base 9
  static long findNthNumber(long N)
  {
    // Stores the Nth number
    long result = 0;
 
    long p = 1;
 
    // Iterate while N is
    // greater than 0
    while (N > 0) {
 
      // Update result
      result += (p * (N % 9));
 
      // Divide N by 9
      N = N / 9;
 
      // Multiply p by 10
      p = p * 10;
    }
     
    // Return result
    return result;
  }
 
  // Driver code 
  static void Main ()
  {
    int N = 9;
    Console.Write(findNthNumber(N));
  }
}
 
// This code is contributed by divyesh072019.


输出:
10

时间复杂度: O(log 9 N)
辅助空间: O(1)