📌  相关文章
📜  如果最后一位为 0,则通过将 N 减 1 来查找在 K 步中形成的数字,否则除以 10

📅  最后修改于: 2022-05-13 01:56:09.201000             🧑  作者: Mango

如果最后一位为 0,则通过将 N 减 1 来查找在 K 步中形成的数字,否则除以 10

给定两个整数NK 。对N执行以下类型的操作:

  • 如果N的最后一位非零,则将数字减一。
  • 如果N的最后一位为零,则将该数字除以10 (即删除最后一位)。

任务是在K 个这样的操作之后打印结果。

例子:

方法:这个问题是基于实现的,类似于数字的最后一位。请按照以下步骤解决给定的问题。

  • 反复检查整数N的最后一位。
  • 如果最后一位0 ,则将N除以10
  • 如果 最后一位不是 0 ,从N中减去1
  • 重复以上步骤K次。

以下是上述方法的实现。

C++
// C++ program for above approach
#include 
using namespace std;
 
// Function to perform operations K times
int decreaseNum(int N, int K)
{
    while (K--) {
        // Last digit is 0
        if (N % 10 == 0)
            N /= 10;
 
        // Last digit is not 0
        else
            N--;
    }
    return N;
}
 
// Driver Code
int main()
{
    // Declaration and initialisation
    int N, K;
    N = 512;
    K = 4;
 
    // Function call
    cout << decreaseNum(N, K);
 
    return 0;
}


Java
// Java program of the above approach
import java.util.*;
class GFG {
 
  // Function to perform operations K times
  public static int decreaseNum(int N, int K)
  {
    while (true) {
      K -= 1;
       
      // Last digit is 0
      if (N % 10 == 0)
        N /= 10;
 
      // Last digit is not 0
      else
        N--;
 
      if (K == 0)
        break;
    }
    return N;
  }
 
  // Driver Code
  public static void main(String args[])
  {
     
    // Declaration and initialisation
    int N, K;
    N = 512;
    K = 4;
 
    // Function call
    System.out.println(decreaseNum(N, K));
 
  }
}
 
    // This code is contributed by rakeshsahni


Python3
# python3 for above approach
 
# def Function to perform operations K times
def decreaseNum(N, K):
 
    while True:
        K -= 1
        # Last digit is 0
        if (N % 10 == 0):
            N //= 10
 
            # Last digit is not 0
        else:
            N -= 1
 
        if K == 0:
            break
 
    return N
 
# Driver Code
if __name__ == "__main__":
 
        # Declaration and initialisation
    N = 512
    K = 4
 
    # Function call
    print(decreaseNum(N, K))
 
    # This code is contributed by rakeshsahni


C#
// C# program for the above approach
using System;
using System.Collections;
 
class GFG
{
 
  // Function to perform operations K times
  public static int decreaseNum(int N, int K)
  {
    while (true) {
      K -= 1;
 
      // Last digit is 0
      if (N % 10 == 0)
        N /= 10;
 
      // Last digit is not 0
      else
        N--;
 
      if (K == 0)
        break;
    }
    return N;
  }
 
  // Driver Code
  public static void Main()
  {
    // Declaration and initialisation
    int N = 512;
    int K = 4;
 
    // Function call
    Console.Write(decreaseNum(N, K));
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript



输出
50

时间复杂度: O(K)
辅助空间: O(1)