Find number formed in K steps by reducing N by 1 if last digit is 0 else divide by 10
Last Updated :
07 Jan, 2022
Given two integers N and K. Perform the following type of operations on N:
- if the last digit of N is non-zero, decrease the number by one.
- if the last digit of N is zero, divide the number by 10 (i.e. remove the last digit).
The task is to print the result after K such operations.
Examples:
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.
Approach: This problem is implementation-based and similar to the Last digit of a number. Follow the steps below to solve the given problem.
- Repeatedly check the last digit of integer N.
- If last digit is 0, divide N by 10.
- If last digit is NOT 0, subtract 1 from N.
- Repeat the above steps K times.
Below is the implementation for the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int decreaseNum( int N, int K)
{
while (K--) {
if (N % 10 == 0)
N /= 10;
else
N--;
}
return N;
}
int main()
{
int N, K;
N = 512;
K = 4;
cout << decreaseNum(N, K);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static int decreaseNum( int N, int K)
{
while ( true ) {
K -= 1 ;
if (N % 10 == 0 )
N /= 10 ;
else
N--;
if (K == 0 )
break ;
}
return N;
}
public static void main(String args[])
{
int N, K;
N = 512 ;
K = 4 ;
System.out.println(decreaseNum(N, K));
}
}
|
Python3
def decreaseNum(N, K):
while True :
K - = 1
if (N % 10 = = 0 ):
N / / = 10
else :
N - = 1
if K = = 0 :
break
return N
if __name__ = = "__main__" :
N = 512
K = 4
print (decreaseNum(N, K))
|
C#
using System;
using System.Collections;
class GFG
{
public static int decreaseNum( int N, int K)
{
while ( true ) {
K -= 1;
if (N % 10 == 0)
N /= 10;
else
N--;
if (K == 0)
break ;
}
return N;
}
public static void Main()
{
int N = 512;
int K = 4;
Console.Write(decreaseNum(N, K));
}
}
|
Javascript
<script>
function decreaseNum(N, K)
{
while (K--)
{
if (N % 10 == 0)
N /= 10;
else
N--;
}
return N;
}
let N, K;
N = 512;
K = 4;
document.write(decreaseNum(N, K));
</script>
|
Time Complexity: O(K)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...