Hi,

I have got an integer as 0010000001.
I need to remove the last 4 digits ie 0001
and the remaining digits is 001000(this is expected)
The truncation of last 4 digit is standard. ie the size of last digits is always 4.
can anybody help me to code this in c++.
Solution: i tried using num/10000 but i dont think this is feasible solution.
Awaiting a better logic.
Thanks

Anu

I have got an integer as 0010000001

Is 0010000001 binary? If it is, just shift right the number of digits to remove.

If it's just a decimal integer then num/10000 seems logical.

commented: its not binary,, its exactly 10 digit number ,so as of now foll.this logic.Thanks +0

I have got an integer as 0010000001.

Just so you're aware, leading zeros are typically truncated as they don't contribute to the value and are conceptually infinite. So your number would be 10000001 unless otherwise formatted to ten digits with leading zeros. That doesn't affect your algorithm, but it's something to keep in mind.

Solution: i tried using num/10000 but i dont think this is feasible solution.

Why don't you think it's a feasible solution?

commented: aware abt the truncation of d leading zeros. In case if the number is 1234567890 and xpected result:123456.Division by 10000 is easier solution and just wanted to know if thr r any other way to get the first 6digits. +0

Do you just need to display a truncated number, or actually change the value?

commented: i need to display the truncated numbers only. +0

Seems like the task could be to use a bitshift operation:

int i = 1;
std::cout << i << std::endl;

i << 1;   // Shift bits to the left
std::cout << i << std::endl;

i << 1;   // Shift bits to the left
std::cout << i << std::endl;

This should display:

1
2
4

What it's doing it shifting the bits in i by one position to the left each time, so i looks like this in binary:

0b00000000 00000000 00000000 00000001
                                    ^

The after the first bitshift, it looks like this:

0b00000000 00000000 00000000 00000010
                                   ^

And then, after the next one:

0b00000000 00000000 00000000 00000100
                                  ^

Note how the 1 is moving. You can shift to the right too, with >>. That should allow you to move the last 4 digits off the number.

commented: Thank u and will try this. +0

Also, you could do it by using a stringstream:

int i=1001010100;
std::stringstream token;
token<<i;
token.str(token.str().substr(0, token.str().size()-4));
token>>i;

this will convert your int to a stringstream object, than, it will remove the last 4 digits and it will convert it back to int.

commented: gr8,thanks a lot +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.