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.
Floor(x / 10^(n))
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
n % 10000
. . 10000?
, , 10. "" , modding 10, , ( 10).
, (%), , n :
12345% 10 ^ 4 = 12345% 10000 = 2345
(/ C/++/Java) n :
12345/10 ^ 4 = 12345/10000 = 1
, , .
, (%), . 11% 3 = 2, 3 11 (9). 2. 41% 10 = 1, 10 41 (40). 1.
, , , . 12345, 1000. 1000 12345 , 345, . , . x% (10 ^ (n)), x , n - , .
. , ?
, - , . , , , , , .
, . , /10. 0b0111, , /2. 0xff/16, 0x0f.
, , , ( ) ( ). , . , , 10 , , , , . ( ) , .
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.
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; }
Source: https://habr.com/ru/post/1711877/More articles:Exceptions and Abstractions - language-agnosticObjective-C - Adding characters to specific parts of a string - objective-cWhy it does not compile in F # - recursionWhat is a good php class for SMTP email? - phpWrite a shell script that finds-greps and prints the file name and contents in 1 line - bashHow to find the value of an enumeration taking into account the arguments that were provided to its constructor? - javameasure linq performance to sql and statistics - performanceParse: lazy initialization and mutually recursive monads in F # - parsingGUI development for J2ME application - javaHow to use sqlite + fdbm library with threads on iPhone - multithreadingAll Articles