What is the best way to remove leading / trailing digits from a number?

If I have a number like 12345 and I want to get 2345, is there a mathematical algorithm that does this? The hack in me wants to convert a number to a string and fine-tune it. I know this will work, but I'm sure there must be a better way, and Google is failing.

Similarly, for 12345, if I want 1234, is there another algorithm that will do this? The best I can think of is Floor(x / 10^(n))where x is the input and n is the number of bits, but I feel that there should be a better way and I just don't see it.

+3
source share
8 answers

Python 3.0:

>>> import math
>>> def remove_most_significant_digit(n, base=10):
...     return n % (base ** int(math.log(n, base)))
...
>>> def remove_least_significant_digit(n, base=10):
...     return int(n // base)
...
>>> remove_most_significant_digit(12345)
2345
>>> remove_least_significant_digit(12345)
1234
+2
source

n % 10000

. . 10000?

, , 10. "" , modding 10, , ( 10).

+9

, (%), , n :

12345% 10 ^ 4 = 12345% 10000 = 2345

(/ C/++/Java) n :

12345/10 ^ 4 = 12345/10000 = 1

+3

, , .

, (%), . 11% 3 = 2, 3 11 (9). 2. 41% 10 = 1, 10 41 (40). 1.

, , , . 12345, 1000. 1000 12345 , 345, . , . x% (10 ^ (n)), x , n - , .

. , ?

+2

, - , . , , , , , .

, . , /10. 0b0111, , /2. 0xff/16, 0x0f.

+1

, , , ( ) ( ). , . , , 10 , , , , . ( ) , .

+1

I think converting to a string and then deleting the first char will not do the trick. I believe that alg performs the div-mod procedure to convert to a string, for optimization you can also make div-mod alg yourself and manipulate it with your needs.

0
source

Here is the C ++ code ... It has not been tested.

int myPow ( int n , int k ){
int ret = 1;
for (int i=0;i<k;++i) ret*=n;
return ret;
}

int countDigits (int n ){
 int count = 0;
 while ( n )++count, n/=10;
return count;
}

int getLastDigits (int number , int numDigits ){
  int tmp = myPow ( 10 , numDigits );
  return number % tmp;
}

int getFirstDigits (int number, numDigits ){
   int tmp = myPow ( 10, countDigits ( number) - numDigits );
   return nuber / tmp;
}
0
source

Source: https://habr.com/ru/post/1711877/


All Articles