Friday, June 29, 2018

WAP to convert an array to number !

Problem statement: wap to convert an array to number.
public class ConvertArrayToNumber {
    public static void main(String args[]) {
        int a[] = {5, 7, 3, 8, 1};
        int a1[] = {5, 7, 3, 8, 1, 4, 4};

        //Test cases
        if (Integer.parseInt(convert(a)) == 57381)
            System.out.println("pass");
        else            System.out.println("Fail");
        if (Integer.parseInt(convert(a1)) == 5738144)
            System.out.println("pass");
        else            System.out.println("Fail");
    }
    public static String convert(int a[]) {
        String temp = "";
        for (int i = 0; i < a.length; i++) {
            temp = temp + a[i];
        }
        return temp;
    }
}

Output: 
pass
pass

public class ConvertArrayToNumber {
    public static void main(String args[]) {
        int a[] = {5, 7, 3, 8, 1};
        int a1[] = {5, 7, 3, 8, 1, 4, 4};
        if (convert(a) == 57381)
            System.out.println("pass");
        else            System.out.println("Fail");
        if (convert(a1) == 5738144)
            System.out.println("pass");
        else            System.out.println("Fail");
    }
    public static int convert(int a[]) {
        String str = a[0] + "";
        int total = 0;
        for (int i : a) {
            total = total * 10 + i;
        }
        return total;
    }
}


No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...