I am learning C in school and am doing a project that involves writing a function(str_subtract_one
) that gets a string containing a positive integer.
The function subtracts 1
from that integer and puts the obtained value in the string.
In the code below, I successfully wrote a function to do that, but the thing is that the input numbers may be larger than the maximum of int
, long
or long long
, so I should not try to convert the string to an integer.
So, without converting the string into int
, long
or long long
, how can I do the same job?
I appreciate any feedback. Thank you so much.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void str_subtract_one(char* num) {
char *end; // to use it in strtol function,
long long as_long = strtoll(num,&end,10); //to convert string to long, use strtol.
sprintf(num, "%lld", as_long - 1); // to convert long into string and now num has a string value
}
int main() {
char nums[] = "2462343434344545";
str_subtract_one(nums);
printf("\nstr_subtract_one function result; %s\n",nums);
return 0;
}
For example if input string is "2323"
, it should output "2322"
.
If "1000"
, output "999"
, etc.
CodePudding user response:
You can use the following algorithm:
- If the last character of the string is a
'9'
, then you can change it to an'8'
. - Otherwise, if the last character of the string is a
'8'
, then you can change it to an'7'
. - Otherwise, if the last character of the string is a
'7'
, then you can change it to an'6'
. - [...]
- Otherwise, if the last character is a
'0'
, you change it to a'9'
and repeat all of the above with the next digit.
If you run out of digits (which will happen if all of the digits are '0'
), you must overwrite the entire string with the new string "-1"
. This will only work if at least 3 bytes have been allocated for the string, otherwise there will be not enough room to write the result, without causing a buffer overflow. For example, if you write
char nums[] = "0";
then trying to write "-1"
into the string will write to the array out of bounds, causing undefined behavior (your program may crash).
For this reason, you would have to write the following instead, if you want to ensure that there is room for writing "-1"
:
char nums[3] = "0";
Note that this algorithm will only work with positive numbers. (In your question, you stated that we can assume that the numbers are positive.)
If you want it to also work with negative numbers, you must first check the sign of the number and then apply the appropriate algorithm. You will need one algorithm for handling positive numbers and one for handling negative numbers (although you may want to try to combine both of them into one algorithm).
In accordance with the community guidelines on homework questions, I will not provide the full solution to your problem at this time. However, I can add code later, if required.
CodePudding user response:
use bn
from openssl. it has no size limitation.