Find First Digit of a Number Using Only Integer Operations

Find first digit of a number using ONLY integer operations

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

In order to access first Digit of an integer dynamically, is using a String or Division more efficient?

Short answer: no-one knows until you profile (benchmark) your code!

Longer answer: modulo + division should be faster than any version involving string converstion but there are exceptions: absent any built-in hardware support, any itoa/to_string implementation needs to perform the same relatively expensive modulo and division you're already performing by necessity (as you're converting from one base to another) in addition to string allocation, so therefore doing only the modulo and division operations should be faster.

This does depend on your platform - if you're using Java or C# then your runtime (the JVM and CLR respectively) implement the ToString operation internally using heavily optimized platform-specific code which will likely be faster than doing the arithmetic yourself even though their version includes string allocation.

Retrieving the first digit of a number

    int number = 534;
int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));

How do i determine the first digit of a number without knowing the number of digits?c++

Assuming a is the input number.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
long a = 42556;
long num;
num=floor(log10(a))+1;
//cout<<num<<" "<<"\n"; //prints the number of digits in the number

cout<<a/(int)pow(10,num-1)<<"\n"; //prints the first digit
cout<<a%10<<"\n"; //prints the last digit

return 0;
}

Live demo here.

Getting each individual digit from a whole integer

You use the modulo operator:

while(score)
{
printf("%d\n", score % 10);
score /= 10;
}

Note that this will give you the digits in reverse order (i.e. least significant digit first). If you want the most significant digit first, you'll have to store the digits in an array, then read them out in reverse order.

How can you get the first digit in an int (C#)?

Here's how

int i = Math.Abs(386792);
while(i >= 10)
i /= 10;

and i will contain what you need



Related Topics



Leave a reply



Submit