Problem | Express without Digit 7

Problem

Write a program to accept a number containing the digit 7 at least once and express it as the sum of two numbers which do not contain the digit 7. The program should first accept the number of test cases and then all the test cases, and finally display the results of all the cases. It is guaranteed that at least one solution exists for any such number and the program should display any one solution.

Analysis

We can express any number X as A + B, where A is obtained by replacing all 7’s in X by 3 and leaving the other digits unchanged, and B is obtained by replacing all 7’s in X by 3 and other digits by 0. For example, 12768735 = 12368335 + 400400.

Output

Enter number of test cases.
3
Enter 3 numbers containing digit 7.
24768
18736770
76767
Case #1: 24768 = 24368 + 400
Case #2: 18736770 = 18336330 + 400440
Case #3: 76767 = 36363 + 40404

Program

/**
 * This program accepts a number containing the digit 7 at least once
 * and expresses it as the sum of two numbers which do not contain 7.
 */
import java.io.*;
public class Number
{
    public static String solution(String N)
    {
        String str1="",str2="";
        char ch=' ';
        for(int i=0;i<N.length();i++)
        {
            ch=N.charAt(i);
            if(ch=='7')
            {
                str1=str1+'3';
                str2=str2+'4';
            }
            else
            {
                str1=str1+ch;
                if(!str2.equals(""))
                    str2=str2+'0';
            }
        }
        if(str2.equals(""))
            str2="0";
        return str1+" + "+str2;
    }
    public static void main()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter number of test cases.");
        int T=Integer.parseInt(br.readLine());
        String ar[]=new String[T];
        System.out.println("Enter "+T+" numbers containing digit 7.");
        for(int i=0;i<T;i++)
            ar[i]=br.readLine();
        for(int i=0;i<T;i++)
            System.out.println("Case #"+(i+1)+": "+ar[i]+" = "+solution(ar[i]));
    }
}

Leave a comment