开发者

How do I remove the first number from an integer?

开发者 https://www.devze.com 2023-01-28 10:42 出处:网络
I need to intake a number like: 200939915 After doing this, which I know how, I need to re开发者_StackOverflow中文版move the first number so it becomes: 00939915

I need to intake a number like: 200939915

After doing this, which I know how, I need to re开发者_StackOverflow中文版move the first number so it becomes: 00939915

What is the best way to do this?


char *c = "200939915";
char *d = c + 1;


I will probably attract the downvoters but here is what I would do:

#include <iostream>
#include <math.h>

int main()
{
    int number;
    std::cin >> number;

    int temp = number;
    int digits = 0;
    int lastnumber = 0;
    while(temp!=0)
    {
        digits++;
        lastnumber = temp % 10;
        temp = temp/10;
    }

    number =  number % (lastnumber * (int)pow(10,digits-1));
    std::cout << number << std::endl;
    return 0;
}

obviously since you want it in c change std::cin to scanf (or whatever) and std::cout to printf (or whatever). Keep in mind though that if you want the two 00 to remain in the left side of the number, Kane's answer is what you should do. Cheers


Here I used an alias (nCopy) for our original integer. Then counted the number of digits till ones place. Say n=1234, inside the while loop, it iterates for 3 times. So count=3.
The n now finally contains the ones place digit (/first digit, here 1) as looping condition is till n>10. Then we use pow function and calculate 103 = 1000. Then subtract it from the alias, 1234-1000 = 234. And finally copy the value to original integer.

#include <iostream>
#include <math.h>
using namespace std;

int main() 
{
    int n; cin >> n;
    int nCopy = n;
    int count = 0;
    while(n>10){
      n/=10; 
      count ++;
    }
    nCopy -= (n * pow(10, count));
    n = nCopy;
    cout << n;
    return 0;
}

Hope it helps :)


To remove the first digit of a integer first reverse the number. now remove the last digit using %10. Now again reverse the number. Now we can see that the first digit of the number will be removed.

0

精彩评论

暂无评论...
验证码 换一张
取 消