Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first digit of a number using ONLY integer operations

Tags:

c#

math

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.

like image 500
Phantom Lobster Avatar asked Sep 25 '18 13:09

Phantom Lobster


2 Answers

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
like image 158
Yves Daoust Avatar answered Oct 21 '22 17:10

Yves Daoust


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

like image 37
alxnull Avatar answered Oct 21 '22 19:10

alxnull