Find first digit of a number using ONLY integer operations

  • A+
Category:Languages

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.

 


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  

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: