You are given an integer and you have to convert it into a string - Hacker Rank Solution.

Please complete the partially completed code in the editor. If your code successfully converts  into a string  the code will print "Good job". Otherwise it will print "Wrong answer".

 can range between  to  inclusive.

Sample Input 0

100

Sample Output 0

Good job

SOLUTION:-

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.close();

        // Convert the integer to a string
        String s = Integer.toString(n);

        // Check if the string can be converted back and matches the original
        if (n == Integer.parseInt(s)) {
            System.out.println("Good job");
        } else {
            System.out.println("Wrong answer");
        }
    }
}



EXPLANATION:

✅ 1. Scanner sc = new Scanner(System.in);

  • We create a Scanner object to take input from the user (from the console).

  • System.in means input is coming from the standard input stream (keyboard).

✅ 2. int n = sc.nextInt();

  • Reads the next integer entered by the user and stores it in the variable n.

✅ 3. sc.close();

  • It's a good practice to close the scanner once you're done using it to free up resources.

✅ 4. String s = Integer.toString(n);

  • Converts the integer n into a String using Integer.toString(n).

  • Example: if n = 100, then s = "100" (now it's a string).

✅ 5. if (n == Integer.parseInt(s)) {

  • Converts the string s back to an integer using Integer.parseInt(s).

  • Compares it with the original integer n.

  • If the conversion was successful, the values should match.

✅ 6. System.out.println("Good job");

  • If the conversion is correct, print "Good job".

❌ 7. System.out.println("Wrong answer");

  • If something went wrong (conversion failed or mismatch), print "Wrong answer".


🧪 Example Run:

Input:

100

Process:

  • n = 100

  • Convert n"100" (String)

  • Convert "100"100 (int)

  • Compare: 100 == 100 → ✅ true

Output:

Good job

Popular posts from this blog

In this problem, you will practice your knowledge on interfaces - Hacker Rank Solution.