Đề bài
Look at every decimal digit of n and return the largest one.
Implement largest_digit(n).
Input
n: A positive integer.
Output
Return the largest digit, from 0 to 9.
Ràng buộc
1 ≤ n ≤ 10¹⁸
Ví dụ
Đầu vào:
n = 352
Kết quả mong đợi:
expected = 5
Đầu vào:
long long n = 352;
Kết quả mong đợi:
long long expected = 5;
Đầu vào:
long n = 352;
Kết quả mong đợi:
long expected = 5;
Giải thích
The digits are 3, 5 and 2; the largest is 5.
Đầu vào:
n = 7
Kết quả mong đợi:
expected = 7
Đầu vào:
long long n = 7;
Kết quả mong đợi:
long long expected = 7;
Đầu vào:
long n = 7;
Kết quả mong đợi:
long expected = 7;
Giải thích
The only digit is 7.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Compare every decimal digit and keep the biggest one seen so far.
Gợi ý 2
Extract digits one by one from the right, or inspect the string characters.
Gợi ý 3
A number containing 9 anywhere immediately sets the answer to 9.
Độ phức tạp mong đợi
O(d) time, O(1) extra space