Maximum digit in a number#8630

Maximum digit in a number (Editorial)

Divide the number by until the result becomes zero. The last digit of each division result corresponds to a digit of the original number . Find the maximum value among these digits.

Algorithm implementation

Read the input value of .

scanf("%lld", &n);

Find the maximum digit of the number in the variable .

res = 0;

Iterate through all the digits of . To do this, repeatedly divide by and extract its last digit d = n \% 10. Among all such digits , determine the maximum value.

while (n > 0)
{
  d = n % 10;
  if (d > res) res = d;
  n = n / 10;
}

Print the answer.

printf("%d\n", res);

Java implementation

import java.util.*;

public class Main 
{
  public static void main(String[] args) 
  {
    Scanner con = new Scanner(System.in);	  
    long n = con.nextLong();
    long res = 0;
    while (n > 0)
    {
      long d = n % 10;
      if (d > res) res = d;
      n = n / 10;
    }

    System.out.println(res);
    con.close();
  }
}

Python implementation

Read the input number as a string.

s = input()

The max() function returns the maximum character in the string.

Print the answer.

print(max(s))