Write a program in Java to find out the second smallest digit of a given number without using arrays
Question: Write a program in Java to find out the second smallest digit of a given number without using arrays.
Welcome to Programming Questions !!!. In this post, I will share the code to find out the second smallest digit of a given number without using the array. This question is frequently asked in google question hub, so in this post, you will get its solution.
Sample Input 1:
Enter Number Here --> 5281036974
Sample Output 1:
The Second Smallest number is 1
Sample Input 2:
Enter Number Here --> 333
Sample Output 2:
All digits of the given number are same, hence there is no second smallest number
Solution code:
import java.util.Scanner;
public class secondSmallest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Number Here --> ");
String number = in.nextLine();
in.close();
int smallest = -1;
int secondSmallest = -1;
boolean flag = true;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < number.length(); j++) {
if (number.charAt(j) - 48 == i && smallest != -1 && smallest != i) {
secondSmallest = i;
flag = false;
}
if (number.charAt(j) - 48 == i)
smallest = i;
}
if (flag == false)
break;
}
if (secondSmallest == -1)
System.out.println("All digits of the given number are same, hence there is no second smallest number");
else
System.out.println("The Second Smallest number is " + secondSmallest);
}
}
I hope that this answer will help you. If you have any question then do not keep it in your mind, put in front of all so that everyone could get its answer.
If you have any questions or want an explanation of any part of the code, feel free to comment below. Subscribe to this blog to get the answers to the latest programming question. You should check my other programming blog too.
Programming Chaska - where you can get several programs in C, C++, and JAVA
Programming Chaska - where you can get several programs in C, C++, and JAVA
Comments
Post a Comment