import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
long n = cin.nextLong();
int s = countDigit(n);
long arr[] = new long[s], num = 0;
for(int i = 0;i<arr.length;i++){
arr[arr.length-1-i] = n % 10;
n /= 10;
}
int i = 0;
if(arr[i] == 9){
i++;
}
for(;i<arr.length;i++){
long t = arr[i];
if(9-t<t){
arr[i] = 9 -t;
}
}
for(int k = 0;k<arr.length;k++){
long fact =1;
for (int j=1;j<=k; j++)
{
fact = fact * 10;
}
num =num + ( arr[arr.length-k-1] *(int) fact) ;
}
System.out.print(num);
}
public static int countDigit(long a){
int count = 0;
while(a>0){
count++;
a /= 10;
}
return count;
}
}===== I have used long still I m getting two test cases wrong, what’s the error in the code
Problem chewbacca and number 2
hi @AbhishekAhlawat1102
The logic behind this Problem was pretty simple as we can invert any digit ( 9 - digit) but we need to invert only such digits that will eventually end up giving the smallest number possible.
So, we should invert only digits greater then or equal to 5 as after inverting them, the result gives us smallest number.
For e.g.,
9 - 5 = 4 viz, smaller than the original number that was 5.
9 - 8 = 1 viz, smaller than the original number that was 8.
but 9 - 1 = 8 viz, greater than the original number that was 1.
Important point to consider is, After inverting any digits their should not be trailing zeros that means, if their is 9 at the starting of the number then it must remain the same
after implementing that check you code for this input
input
932711047202
output
932211042202
yes my code is not working right can u please make the code right because i m stuck in the code
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
@AbhishekAhlawat1102
import java.util.*;
public class temp {
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
long n = cin.nextLong();
int s = countDigit(n);
long arr[] = new long[s], num = 0;
for (int i = 0; i < arr.length; i++) {
arr[arr.length - 1 - i] = n % 10;
n /= 10;
}
int i = 0;
if (arr[i] == 9) {
i++;
}
for (; i < arr.length; i++) {
long t = arr[i];
if (9 - t < t) {
arr[i] = 9 - t;
}
}
long fact = 10;
for (int k = 0; k < arr.length; k++) {
num = num*fact +arr[k];
}
System.out.print(num);
}
public static int countDigit(long a) {
int count = 0;
while (a > 0) {
count++;
a /= 10;
}
return count;
}
}
if you have any doubt in this code do ask me.