如果最后一位为 0,则通过将 N 减 1 来查找在 K 步中形成的数字,否则除以 10
给定两个整数N和K 。对N执行以下类型的操作:
- 如果N的最后一位非零,则将数字减一。
- 如果N的最后一位为零,则将该数字除以10 (即删除最后一位)。
任务是在K 个这样的操作之后打印结果。
例子:
Input: N = 512, K = 4
Output: 50
Explanation: Following are the operations performed K times to get the desired result.
Operation 1: Last digit of N i.e. 2 != 0. N is reduced by 1. ( N = 512 – 1 i.e. 511).
Operation 2: Last digit of N i.e. 1 != 0. N is reduced by 1. (N = 511 – 1 i.e. 510).
Operation 3: Last digit of N is 0. N is divided by 10. ( N = 510/10 i.e. 51).
Operation 4: Last digit of N i.e. 2 != 0. N is reduced by 1. (N = 51 – 1 i.e. 50).
Therefore, after 4 operations N = 50.
Input: N = 100, K = 2
Output: 1
Explanation: N is divided by 10 two times.
方法:这个问题是基于实现的,类似于数字的最后一位。请按照以下步骤解决给定的问题。
- 反复检查整数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)