First Digit of Four-Digit Number
Programming Basics · C++
TASK
Problem
Given a four-digit non-negative integer `n`, print its thousands digit (the first decimal digit).
EXAMPLE
Example
1234
1
LIMITS
Constraints
1000 ≤ n ≤ 9999.
LEARN
Theory for this problem
+
Repeated division by powers of 10 and `% 10` isolate decimal digits without converting the number to a string.
Connection to “First Digit of Four-Digit Number”: here, intermediate values are best kept in named variables so the formula stays readable and data types remain clear.
NEED HELP?
Hints
+
['Extract the digits first, then combine or compare them.', 'After solving “First Digit of Four-Digit Number”, verify the algorithm on your own small example and on an allowed boundary case. Print only the required result with no extra text.']
ANSWER
Solution
+
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
cout << n / 1000 << '\n';
return 0;
}