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?
If you want to append any number of digits, multiply the int by pow(10, log10(yourDigits) + 1) .
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.
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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With