Last Updated: 15 Apr, 2021

Single Digit Change

Easy
Asked in company
Amazon

Problem statement

You are given a positive integer ‘NUM’ consisting only of digits ‘6’ and ‘9’. You can change at most one digit (i.e ‘6’ to ‘9’, or ‘9’ to ‘6’). Your task is to find and return the maximum number you can obtain.

Input Format:
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case will contain a single integer ‘NUM’.
Output Format:
For each test case, return the maximum number you can get by changing at most one digit as described above.
Note:
You don’t need to print anything; It has already been taken care of.
Constraints:
1 <= T <= 50
6 <= ‘NUM’ <= 10^9
‘NUM’ has only digits 6 and 9.

Time limit: 1 sec

Approaches

01 Approach

The idea is to find the leftmost digit which is 6, and change it to 9, if all digits are 9 then we do not change any digit. The easiest way to do it is to first convert ‘NUM’ in a string using the inbuilt methods like to_string() in C++, str(), we will use cahr array in java because String is immutable in java and convert int to char Array, then replace the first occurrence of ‘6’ to ‘9’ and then again convert it to an integer using stoi() in C++, int() in python, and Integer.parseInt in java and return it. 

 

The steps are as follows:

  1. Convert ‘NUM’ to string, and let this string be ‘NUMSTR’.
  2. Iterate over ‘NUMSTR’, if the current character is ‘6’, then replace it with ‘9’ and break the loop.
  3. Return ‘NUMSTR’ by converting it to an equivalent integer.