Chewbacca and Number [codingblocks]

Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t.

Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.

Input Format

The first line contains a single integer x (1 ≤ x ≤ 10^18) — the number that Luke Skywalker gave to Chewbacca.

Constraints

x <= 100000000000000000

Output Format

Print the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes.

Sample Input

4545

Sample Output

4444

Explanation

There are many numbers form after inverting the digit. For minimum number, check if inverting digit is less than or greater than the original digit. If it is less, then invert it otherwise leave it.


Java Code:

Learning:
Check the corner case really well, for example see test case : 9999999, 1000000



import java.util.*;
public class Main {
    public static Scanner scan = new Scanner(System.in);
    public static void main(String[] args) {
        int testCases = scan.nextInt();
        while (testCases-- > 0) {
            long num = scan.nextLong();
            System.out.println(ChewbaccaAndNumber(num));
        }
    }

    private static long ChewbaccaAndNumber(long num) {
        int length = countDigit(num);
        long[] arr = new long[length];
        fillArray(arr, num);

        for (int i=0; i<arr.length; i++) {
            long value = arr[i];
            if(value >= 5) {
                if (i == 0 && value == 9) continue;
                arr[i] = 9 - value;
            }
        }
        return arrayToNum(arr);
    }

    private static long arrayToNum(long[] arr) {
        long num = 0;
        for (int i=0; i<arr.length; i++) {
            num = num*10 + arr[i];
        }
        return num;
    }

    private static void fillArray(long[] arr, long num) {
        int index = arr.length;
        while (num !=0 ) {
            long digit = num%10;
            arr[--index] = digit;
            num = num/10;
        }
    }

    private static int countDigit(long num) {
        int count = 0;
        while (num != 0) {
            count++;
            num = num/10;
        }
        return count;
    }
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )