I can't understand how to solve the problem that the teacher gave me.
Given a number N (0 <= N <= 100), find its first digit.
For example:
input: 100
result: 1
input: 46
result: 4
input: 3
result: 3
It seemed easy at first, but (as the teacher said) it should be done using ONLY integer data types (in other words, using +
, -
, *
, /
and %
operators). Is it even possible to do it this way?
I just can't realize how to extract the first digit from a variable-length number without using things like log10, conditions, "while" loop or string conversion.
Without any conditionals:
int H= N / 100; // Hundreds digit
int T= (N / 10) % 10; // Tens digit
int U= N % 10; // Units digit
int h= H; // Hundreds flag
int t= (T + 9) / 10 * (1 - h); // Tens flag
int u= (1 - t) * (1 - h); // Units flag
int Answer= u * U + t * T + h * H; // Combination
Edit: Now tested for 0 and 100:
var result = n / 10 * (1 - n / 100) + n / 100 + (109 - n) / 100 * n;
How it works:
n | n / 10 * (1 - n / 100) | n / 100 | (109 - n) / 100 * n ----------------------------------------------------------------- 10 - 99 | 1 - 9 | 0 | 0 ----------------------------------------------------------------- 100 | 0 | 1 | 0 ----------------------------------------------------------------- 0 - 9 | 0 | 0 | 0 - 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With