Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append digit to an int without converting to string?

Is there a safe way of adding a digit at the end of an integer without converting it to a string and without using stringstreams ?

I tried to google the answer for this and most solutions suggested converting it to a string and using stringstreams but I would like to keep it as an integer to ensure data integrity and to avoid converting types.
I also read a solution which suggested to multiply the int by 10 and then adding the digit, however this might cause an integer overflow.
Is this safe to do or is there a better method for doing this? And if I do this multiply by 10 and add the digits solution, what precautions should I take?

like image 953
nmuntz Avatar asked May 26 '09 19:05

nmuntz


People also ask

Can you append to an integer?

If you want to append any number of digits, multiply the int by pow(10, log10(yourDigits) + 1) .

How do you append a digit to a number in Java?

Approach: Find the number appended in the end of the string say num and append a 0 in the end which is the least digit possible i.e. num = num * 10. Now find the length of the remaining string ignoring the numeric from the end say len. Now the digit which must be appended will be digit = len – num.

Can I use isDigit for int?

The isdigit() is declared inside ctype. h header file. It is used to check whether the entered character is a numeric character[0 – 9] or not. It takes a single argument in the form of an integer and returns the value of type int.


2 Answers

Your best bet is the multiplication by 10 and addition of the value. You could do a naive check like so:

assert(digit >= 0 && digit < 10);
newValue = (oldValue * 10) + digit;
if (newValue < oldValue)
{
    // overflow
}
like image 182
user7116 Avatar answered Oct 22 '22 15:10

user7116


To prevent overflow:

if ((0 <= value) && (value <= ((MAX_INT - 9) / 10))) {
    return (value * 10) + digit;
}

In place of MAX_INT, you could use std::numeric_limits<typeof(value)>::max() or similar, to support types other than int.

like image 26
Steve Jessop Avatar answered Oct 22 '22 16:10

Steve Jessop