Survival of the Biggest
by CodeChum Admin
Looping a number and taking away each digit of it is so much fun, but I wanted to try out a much more complex task: getting the largest digit among them all.
Think you can handle the job?
Instructions:
Input a non-zero positive integer.
Using the same concept as the previous problem, figure out how to separate the digits of a number and determine which of the digits is the largest one, using a while. Afterwards, print the largest digit.
Tip #1: Create another variable that will hold the largest digit. Initial its value to a negative integer, like -1, outside the loop.
Tip #2: Everytime you get the rightmost digit, check if it is greater than the current largest digit. If it is, set it as the new largest digit.
Input
A line containing an integer.
214
Output
A line containing an integer.
4
SOLUTION TO THE ABOVE QUESTION
SOLUTION CODE
package com.company;
import java.util.*;
class Main{
public static void main(String arg[])
{
//propmt the user to enter a number
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
//lets convert the number to a string
String number_string = Integer.toString(number);
int number_length = number_string.length();
// Now lets loop through the string to get the largets digit
int maximum = 0;
for(int i = 0; i< number_length; i++)
{
if(Character.getNumericValue(number_string.charAt(i))>maximum)
{
maximum = Character.getNumericValue(number_string.charAt(i));
}
}
//Now lets print the largest digit
System.out.println("The largest digit in our number "+number+" is "+maximum);
}
}
SAMPLE OUTPUT
Comments
Leave a comment