Remove digits in number

I know how to remove digits in number from right to left.
For example: the number 319. If I do (number /= 10), I get 31.

My question is how can I remove digits in number from left to right.
For example: the number 319. If I will do something, I will get the number 19.

Thank you :)
Last edited on
you can use shift operator
@kulkarnisr : How?
Last edited on
Shift operator works only on the binary level, i.e., divide by 2, multiply by 2 etc.

For the OP's requirement % (remainder) operator is suitable.
319 % 1000 = 319.
319 % 100 = 19.
319 % 10 = 9.
@abhishekm71 : I gave that number only for example, I dont pick the number, so I dont know how to devide it.
If the number is 168735
and I do (168735 % 100) I will get 35, I wont get all the numbers besides 1 from the left like u did.

I hope u understand me.
Last edited on
Well then, add some logic to determine how big the number is first.
Then perhaps you will either have to count the number of digits in the number (using a loop) and apply % accordingly, or take input as a string if you can, modify it as wished and use stringstream to convert it into decimal whenever required.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <math.h>

using namespace std;

int DropLeadingDigit(int number){return(number % (int) pow((double) 10, (double) floor(log((double) number) / log((double) 10))));}

int main(){
    int number;
    while(cin >> number) cout << DropLeadingDigit(number) << endl << endl;
    
    return(0);
}


floor(log(a) / log(b)) + 1 is the number of digits of a in base b
Last edited on
@mario0815

If you do log10(num)+1, you get the number of digits in the number...
1
2
3
4
5
6
unsigned int remove_most_significant_digit( unsigned int n )
{
    int divisor = 1 ;
    for( int v = n ; v > 9 ; v /= 10 ) divisor *= 10 ;
    return n % divisor ;
}
1
2
3
4
5
6
unsigned remove_leftmost_digit(unsigned n)
{
    static char temp[11];
    sprintf(temp, "%d", n);
    return atoi(temp+1);
}

1
2
3
4
5
6
7
8
9
10
unsigned remove_leftmost_digit(unsigned n)
{
    // static char temp[11];
    static char temp[ std::numeric_limits<unsigned int>::digits10 + 2 ] ;

    // sprintf(temp, "%d", n);
    sprintf(temp, "%u", n) ;

    return atoi(temp+1);
}
why std::numeric_limits<unsigned int>::digits10 + 2 ?
why not std::numeric_limits<unsigned int>::digits10 + 1 ?

EDIT: I know that '\0' occupies 1 extra location. Any other character that is needed?
Last edited on
oops..! sorry ziv...
@abhishek thanks
> I know that '\0' occupies 1 extra location. Any other character that is needed?

The number of decimal digits in std::numeric_limits<unsigned int>::max() is one greater than the value of std::numeric_limits<unsigned int>::digits10
ok.. thanks JLBorges!
Topic archived. No new replies allowed.