I am solving reverse integer problem in leetcode in c language.But it gives runtime error on line sum=sum+rem*10;.
runtime error: signed integer overflow: 964632435 * 10 cannot be represented in type 'int'
Here is the code.
#define INT_MAX 2147483647
#define INT_MIN -2147483648
int reverse(int x){
int sum=0,rem=0;
int p;
if(x > INT_MAX || x < INT_MIN){return 0;}
if(x==0){return 0;}
if(x<0){p=x;x=abs(x);}
while(x%10==0){x=x/10;}
while(x>0){
rem=x%10;
if(sum > INT_MAX || sum*(-1) < INT_MIN){return 0;}
sum=sum*10+rem;
x/=10;
}
if(p<0){sum=sum*(-1);return sum;}
else{return sum;}
}
One way - which isn't performance optimal but simple - is to convert the integer to a string and then revert the string and then convert back to integer.
The below solution is for positive integers - I'll leave it to OP to extend it to handle negative integers.
Could look like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
int reverse(const int n)
{
if (n < 0)
{
printf("Handling of negative integers must be added\n");
exit(1);
}
char tmp1[100];
char tmp2[100] = { 0 };
sprintf(tmp1, "%d", n);
printf("Input : %s\n", tmp1);
size_t sz = strlen(tmp1);
for (size_t i = 0; i < sz; ++i)
{
tmp2[i] = tmp1[sz-i-1];
}
int result = tmp2[0] - '0';
char* p = tmp2+1;
while(*p)
{
if ((INT_MAX / 10) < result)
{
printf("oh dear: %d can't be reversed to int\n", n);
exit(1);
}
result = result * 10;
if ((INT_MAX - (*p - '0')) < result)
{
printf("oh dear: %d can't be reversed to int\n", n);
exit(1);
}
result += *p - '0';
p++;
}
return result;
}
int main()
{
printf("Output: %d\n", reverse(123));
printf("Output: %d\n", reverse(123456789));
printf("Output: %d\n", reverse(1234567899));
return 0;
}
Output:
Input : 123
Output: 321
Input : 123456789
Output: 987654321
Input : 1234567899
oh dear: 1234567899 can't be reversed to int
But it gives runtime error on line sum=sum+rem*10;.
To test for potential int overflow of positive sum, rem, compare against INT_MAX/10 and INT_MAX%10 beforehand.
if (sum >= INT_MAX / 10 && (sum > INT_MAX / 10 || rem > INT_MAX % 10)) {
// overflow
} else {
sum = sum * 10 + rem;
}
Handling negatives
Watch out for x = INT_MIN ... x = -x;. That is int overflow and undefined behavior.
Sometimes it is fun to solve such int problems of positive and negative numbers by converting the positive numbers to negative ones embrace the dark side - its your only hope. (maniacal laughter)
There are more int values less than zero than there are int values more than zero - by one. So x = -x is always well defined when x > 0.
// C99 or later code
#include <limits.h>
int reverse(int x) {
int x0 = x;
if (x0 > 0) {
x = -x; // make positive values negative, embrace the dark side
}
int reversed = 0;
while (x < 0) {
int rem = x % 10;
x /= 10;
if (reversed <= INT_MIN / 10
&& (reversed < INT_MIN / 10 || rem < INT_MIN % 10)) {
// overflow
return 0;
}
reversed = reversed * 10 + rem;
}
if (x0 > 0) {
if (reversed < -INT_MAX) {
// overflow
return 0;
}
reversed = -reversed;
}
return reversed;
}
Test code
#include <stdio.h>
int main() {
int x[] = {0, 1, -1, 42, 123456789, INT_MAX/10*10+1, INT_MIN/10*10-1,INT_MAX, INT_MIN};
size_t n = sizeof x / sizeof x[0];
for (size_t i = 0; i < n; i++) {
printf("Attempting to reverse %11d ", x[i]);
printf("Result %11d\n", reverse(x[i]));
}
}
Sample output
Attempting to reverse 0 Result 0
Attempting to reverse 1 Result 1
Attempting to reverse -1 Result -1
Attempting to reverse 42 Result 24
Attempting to reverse 123456789 Result 987654321
Attempting to reverse 2147483641 Result 1463847412
Attempting to reverse -2147483641 Result -1463847412
Attempting to reverse 2147483647 Result 0
Attempting to reverse -2147483648 Result 0
First, you should not be defining your own values for INT_MAX and INT_MIN. You should instead #include <limits.h> which defines these value.
Second, this:
sum > INT_MAX
Will never be true because sum can never hold a value larger than INT_MAX. So you can't perform an operation and then check afterward if it overflowed. What you can do instead is check the operation first and do some algebra that prevents overflow.
if ( INT_MAX / 10 < sum) return 0;
sum *= 10;
if ( INT_MAX - rem < sum) return 0;
sum += rem;
Related
My assignment is to create a function that displays the number entered as a parameter. The function has to be able to display all possible values within an inttype variable. write() is the only allowed function.
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_putnbr(int nb)
{
if (nb < 0)
{
ft_putchar('-');
ft_putchar(-nb + '0');
}
if ( nb > 0)
{
ft_putchar(nb + '0');
}
}
I wrote this but obviously it doesn't work for integers that have 2 or more digits, how can I display them as a string?
write is the only allowed function.
A more general solution would use a loop to handle 10s, 100s, etc. Try dividing by the largest power-of-10 and then 1/10 of that, etc.
To handle all int is a little tricky. Beware of code that does -INT_MIN as that is undefined behavior (UB). Instead, use the negative side of int after printing the sign as there are more negative int than positive ones.
#if INT_MAX == 2147483647
# define INT_POW_MAX (1000 * 1000 * 1000)
#elif INT_MAX == 32767
# define INT_POW_MAX (10 * 1000)
#else
// For greater portability, additional code needed
# error "TBD code"
#endif
void ft_putnbr(int nb) {
if (nb < 0) {
// Do not use -nb as that is UB when nb == INT_MIN
ft_putchar('-');
} else {
nb = -nb;
}
// At this point, nb <= 0
int pow10n = -INT_POW_MAX;
// Skip leading 0 digits.
while (pow10n < nb) {
pow10n /= 10;
}
// Print the rest.
do {
int q = pow10n ? nb/pow10n : nb;
ft_putchar(q + '0');
nb -= q*pow10n;
pow10n /= 10;
} while (pow10n);
}
Passes test harness.
A test harness for candidate solutions:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#define ft_putchar putchar
void ft_putnbr(int nb) {
// Your code here
}
void test(int i) {
printf("%12d ", i);
ft_putnbr(i);
printf("\n");
}
int main() {
int a[] = { INT_MIN, 0, 1, 2, 9, 10, 11,42, INT_MAX - 1, INT_MAX };
size_t n = sizeof a / sizeof a[0];
for (size_t i = 0; i < n ; i++) {
if (a[i] > 0) test(-a[i]);
test(a[i]);
}
}
Expected output
-2147483648 -2147483648
0 0
-1 -1
1 1
-2 -2
2 2
-9 -9
9 9
-10 -10
10 10
-11 -11
11 11
-42 -42
42 42
-2147483646 -2147483646
2147483646 2147483646
-2147483647 -2147483647
2147483647 2147483647
A recursive solution.
It also avoids -INT_MIN.
void putint(int nb) {
if (nb < 0) {
ft_putchar('-');
if (nb == INT_MIN) {
putint(nb / -10);
nb %= -10;
}
nb = -nb;
}
if (nb >= 10) {
putint(nb/ 10);
nb %= 10;
}
ft_putchar(nb + '0');
}
I wrote this code to find the prime factorization of a number. I just cannot figure out the last part. If x is entered as a double or float, the program should print an error message and terminate. How do I achieve this?
#include <stdio.h>
int main()
{
int x, i;
printf("Enter an integer: ");
scanf("%d", &x);
if (x <= 1)
{
return 1;
}
printf("The prime factorization of %d is ", x);
if (x > 1)
{
while (x % 2 == 0)
{
printf("2 ");
x = x / 2;
}
for (i = 3; i < 1009; i = i + 2)
{
while (x % i == 0)
{
printf("%d ", i);
x = x / i;
}
}
}
return 0;
}
Your starting point should cover all desired and undesired cases so you should take float number from a user, not int. Then, you should check whether whole decimal part of the number is 0. That is, if all of them equals 0, the user want to provide an int number instead of float.
First step is to declare a float number:
float y;
After, take its value from the user:
scanf("%f", &y);
Second step is to check whether it is int or float. There are many ways for this step. For example, I find roundf() function useful. It takes a float number and computes the nearest integer to this number. So if the nearest integer is the number itself then the number has to be int. Right?
if(roundf(y)!=y)
If you are sure it is an int, you can move onto the third step: convert float type to int type. It is called type-casting. This step is required for the remaining part of your program because in your algorithm you manipulate the number with int type so just convert it to int:
x = (int)y;
After adding the line above, you can use the rest of code which you typed. I give the whole program:
#include <stdio.h>
#include <math.h>
int main()
{
int x,i;
float y;
printf("Enter an integer: ");
scanf("%f", &y);
if(roundf(y)!=y){
printf("%f is not an integer!",y);
return 1;
}
else{
x = (int)y;
}
if (x <= 1)
{
printf("%d <= 1",x);
return 1;
}
else
{
printf("The prime factorization of %d is ", x);
while (x%2 == 0)
{
printf("2 ");
x = x / 2;
}
for ( i = 3; i < 1009; i = i + 2)
{
while (x%i == 0)
{
printf("%d ",i);
x = x / i;
}
}
}
return 0;
}
The use of scanf() is a bit tricky, I would avoid it to scan user generated input at almost all cost. But nevertheless here is a short overview for how to get the errors of scanf()
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(void)
{
int x, i, scanf_return;
printf("Enter an integer: ");
/* Reset "errno". Not necessary here, just in case. */
errno = 0;
/* scanf() returns a value in case of an error */
scanf_return = scanf("%d", &x);
/*
* scanf() returns "EOF" if it didn't find all what you wanted or
* and error happened.
* It sets "errno" to the value of the actual error. See manpage
* for all of the details.
*/
if (scanf_return == EOF) {
/*
* The error is connected to the stream, so we can differ between
* an error within scanf() and and error with the input stream
* (here: stdin)
*/
if (ferror(stdin)) {
fprintf(stderr, "Something went wrong while reading stdin: %s\n", strerror(errno));
exit(EXIT_FAILURE);
} else {
/* e.g. a conversion error, a float instead of an integer, letters
instead of a decimal number */
fprintf(stderr, "Something went wrong within scanf()\n");
exit(EXIT_FAILURE);
}
}
/*
* If no error occurred, the return holds the number of objects
* scanf() was able to read. We only need one, but it would throw an
* error if cannot find any objects, so the check is here for
* pedagogical reasons only.
*/
if (scanf_return != 1) {
fprintf(stderr, "Something went wrong within scanf(): wrong number of objects read.\n");
exit(EXIT_FAILURE);
}
if (x <= 1) {
fprintf(stderr, "Input must be larger than 1!\n");
exit(EXIT_FAILURE);
}
printf("The prime factorization of %d is ", x);
/* No need for that test, x is already larger than one at this point. */
/* if (x > 1) { */
while (x%2 == 0) {
printf("2 ");
x = x / 2;
}
for (i = 3; i < 1009; i = i + 2) {
while (x%i == 0) {
printf("%d ",i);
x = x / i;
}
}
/* } */
/* Make it pretty. */
putchar('\n');
exit(EXIT_SUCCESS);
}
Does it work?
$ ./stackoverflow_003
Enter an integer: 1234
The prime factorization of 1234 is 2 617
$ factor 1234
1234: 2 617
$ ./stackoverflow_003
Enter an integer: asd
Something went wrong within scanf(): wrong number of objects read.
$ ./stackoverflow_003
Enter an integer: 123.123
The prime factorization of 123 is 3 41
No, it does not work. Why not? If you ask scanf() to scan an integer it grabs all consecutive decimal digits (0-9) until there is no one left. The little qualifier "consecutive" is most likely the source of your problem: a floating point number with a fractional part has a decimal point and that is the point where scanf() assumes that the integer you wanted ended. Check:
$ ./stackoverflow_003
Enter an integer: .123
Something went wrong within scanf(): wrong number of objects read
How do you find out? #weather-vane gave one of many ways to do so: check if the next character after the integer is a period (or another decimal separator of your choice):
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(void)
{
int x, i, scanf_return;
char c = -1;
printf("Enter an integer: ");
/* Reset "errno". Not necessary here, just in case. */
errno = 0;
/* scanf() returns a value in case of an error */
scanf_return = scanf("%d%c", &x, &c);
/*
* scanf() returns "EOF" if it didn't find all what you wanted or
* and error happened.
* It sets "errno" to the value of the actual error. See manpage
* for all of the details.
*/
if (scanf_return == EOF) {
/*
* The error is connected to the stream, so we can differ between
* an error within scanf() and and error with the input stream
* (here: stdin)
*/
if (ferror(stdin)) {
fprintf(stderr, "Something went wrong while reading stdin: %s\n", strerror(errno));
exit(EXIT_FAILURE);
} else {
/* e.g. a conversion error, a float instead of an integer, letters
instead of a decimal number */
fprintf(stderr, "Something went wrong within scanf()\n");
exit(EXIT_FAILURE);
}
}
/*
* If no error occurred, the return holds the number of objects
* scanf() was able to read. We can use this information now.
* If there is a period (actually any character) after the integer
* it returns 2 (assuming no error happened, of course)
*/
/* If no integer given, the following character ("%c") gets ignored. */
if (scanf_return == 0) {
fprintf(stderr, "Something went wrong within scanf(): no objects read.\n");
exit(EXIT_FAILURE);
}
/* Found two objects, check second one which is the character. */
if (scanf_return == 2) {
if (c == '.') {
fprintf(stderr, "Floating point numbers are not allowed.\n");
exit(EXIT_FAILURE);
}
}
if (x <= 1) {
fprintf(stderr, "Input must be larger than 1!\n");
exit(EXIT_FAILURE);
}
printf("The prime factorization of %d is ", x);
/* No need for that test, x is already larger than one at this point. */
/* if (x > 1) { */
while (x%2 == 0) {
printf("2 ");
x = x / 2;
}
for (i = 3; i < 1009; i = i + 2) {
while (x%i == 0) {
printf("%d ",i);
x = x / i;
}
}
/* } */
/* Make it pretty. */
putchar('\n');
exit(EXIT_SUCCESS);
}
Check:
$ ./stackoverflow_003
Enter an integer: 123
The prime factorization of 123 is 3 41
$ ./stackoverflow_003
Enter an integer: 123.123
Floating point numbers are not allowed.
$ ./stackoverflow_003
Enter an integer: .123
Something went wrong within scanf(): no objects read.
Looks good enough for me. With one little bug:
$ ./stackoverflow_003
Enter an integer: 123.
Floating point numbers are not allowed
But I think I can leave that as an exercise for the dear reader.
You can try this simple C99 implementation of Pollard Rho algorithm :
// Integer factorization in C language.
// Decompose a composite number into a product of smaller integers.
unsigned long long pollard_rho(const unsigned long long N) {
// Require : N is a composite number, not a square.
// Ensure : you already performed trial division up to 23.
// Option : change the timeout, change the rand function.
static const int timeout = 18;
static unsigned long long rand_val = 2994439072U;
rand_val = (rand_val * 1025416097U + 286824428U) % 4294967291LLU;
unsigned long long gcd = 1, a, b, c, i = 0, j = 1, x = 1, y = 1 + rand_val % (N - 1);
for (; gcd == 1; ++i) {
if (i == j) {
if (j >> timeout)
break;
j <<= 1;
x = y; // "x" takes the previous value of "y" when "i" is a power of 2.
}
a = y, b = y; // computes y = f(y)
for (y = 0; a; a & 1 ? b >= N - y ? y -= N : 0, y += b : 0, a >>= 1, (c = b) >= N - b ? c -= N : 0, b += c);
y = (1 + y) % N; // function f performed f(y) = (y * y + 1) % N
for (a = y > x ? y - x : x - y, b = N; (a %= b) && (b %= a););
gcd = a | b; // the GCD(abs(y - x), N) was computed
// it continues until "gcd" is a non-trivial factor of N.
}
return gcd;
}
Usually you performed some trial division before calling the algorithm
The algorithm isn't designed to receive a prime number as input
Two consecutive calls may not result in the same answer
Alternately, there is a pure C quadratic sieve which factors numbers from 0 to 300-bit.
If in doubt about the primality of N you can use a C99 primality checker :
typedef unsigned long long int ulong;
ulong mul_mod(ulong a, ulong b, const ulong mod) {
ulong res = 0, c; // return (a * b) % mod, avoiding overflow errors while doing modular multiplication.
for (b %= mod; a; a & 1 ? b >= mod - res ? res -= mod : 0, res += b : 0, a >>= 1, (c = b) >= mod - b ? c -= mod : 0, b += c);
return res % mod;
}
ulong pow_mod(ulong n, ulong exp, const ulong mod) {
ulong res = 1; // return (n ^ exp) % mod
for (n %= mod; exp; exp & 1 ? res = mul_mod(res, n, mod) : 0, n = mul_mod(n, n, mod), exp >>= 1);
return res;
}
int is_prime(ulong N) {
// Perform a Miller-Rabin test, it should be a deterministic version.
const ulong n_primes = 9, primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23};
for (ulong i = 0; i < n_primes; ++i)
if (N % primes[i] == 0) return N == primes[i];
if (N < primes[n_primes - 1]) return 0;
int primality = 1, a = 0;
ulong b;
for (b = N - 1; ~b & 1; b >>= 1, ++a);
for (ulong i = 0; i < n_primes && primality; ++i) {
ulong c = pow_mod(primes[i], b, N);
if (c != 1) {
for (int j = a; j-- && (primality = c + 1 != N);)
c = mul_mod(c, c, N);
primality = !primality;
}
}
return primality;
}
To try it there is a factor function :
// return the number that was multiplied by itself to reach N.
ulong square_root(const ulong num) {
ulong res = 0, rem = num, a, b;
for (a = 1LLU << 62 ; a; a >>= 2) {
b = res + a;
res >>= 1;
if (rem >= b)
rem -= b, res += a;
}
return res;
}
ulong factor(ulong num){
const ulong root = square_root(num);
if (root * root == num) return root ;
const ulong n_primes = 9, primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23};
for (ulong i = 0; i < n_primes && primes[i] <= root; ++i)
if (num % primes[i] == 0) return primes[i];
if (is_prime(num))
return 1 ;
return pollard_rho(num);
}
Which is completed by the main function :
#include <assert.h>
int main(void){
for(ulong i = 2; i < 63; ++i){
ulong f = factor(i);
assert(f <= 1 || f >= i ? is_prime(i) : i % f == 0);
ulong j = (1LLU << i) - 1 ;
f = factor(j);
assert(f <= 1 || f >= j ? is_prime(j) : j % f == 0);
j = 1 | pow_mod((ulong) &main, i, -5);
f = factor(j);
assert(f <= 1 || f >= j ? is_prime(j) : j % f == 0);
}
}
There are some problems in your code:
you do not check the return value of scanf, so you cannot detect invalid or missing input and will have undefined behavior in those cases.
you only test divisors up to 1009, so composite numbers with larger prime factors do not produce any output.
prime numbers larger than 1009 do not produce any output.
you should probably output a newline after the factors.
Testing and reporting invalid input such as floating point numbers can be done more easily by reading the input as a full line and parsing it with strtol().
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char input[120];
char ch;
char *p;
long x, i;
int last_errno;
printf("Enter an integer: ");
if (!fgets(input, sizeof input, stdin)) {
fprintf(stderr, "missing input\n");
return 1;
}
errno = 0;
x = strtol(input, &p, 0);
last_errno = errno;
if (p == input || sscanf(p, " %c", &ch) == 1) {
fprintf(stderr, "invalid input: %s", input);
return 1;
}
if (last_errno == ERANGE) {
fprintf(stderr, "number too large: %s", input);
return 1;
}
if (x < 0) {
fprintf(stderr, "number is negative: %ld\n", x);
return 1;
}
if (x <= 1) {
return 1;
}
printf("The prime factorization of %ld is", x);
while (x % 2 == 0) {
printf(" 2");
x = x / 2;
}
for (i = 3; x / i >= i;) {
if (x % i == 0) {
printf(" %ld", i);
x = x / i;
} else {
i = i + 2;
}
}
if (x > 1) {
printf(" %ld", x);
}
printf("\n");
return 0;
}
Problem statement :
Given a 32-bit signed integer, reverse digits of an integer.
Note: Assume we are dealing with an environment that could only store
integers within the 32-bit signed integer range: [ −2^31, 2^31 − 1]. For
the purpose of this problem, assume that your function returns 0 when
the reversed integer overflows.
I'm trying to implement the recursive function reverseRec(), It's working for smaller values but it's a mess for the edge cases.
int reverseRec(int x)
{
if(abs(x)<=9)
{
return x;
}
else
{
return reverseRec(x/10) + ((x%10)*(pow(10, (floor(log10(abs(x)))))));
}
}
I've implemented non recursive function which is working just fine :
int reverse(int x)
{
long long val = 0;
do{
val = val*10 + (x%10);
x /= 10;
}while(x);
return (val < INT_MIN || val > INT_MAX) ? 0 : val;
}
Here I use variable val of long long type to check the result with MAX and MIN of signed int type but the description of the problem specifically mentioned that we need to deal within the range of 32-bit integer, although somehow it got accepted but I'm just curious If there is a way to implement a recursive function using only int datatype ?
One more thing even if I consider using long long I'm failing to implement it in the recursive function reverseRec().
If there is a way to implement a recursive function using only int datatype ?
(and) returns 0 when the reversed integer overflows
Yes.
For such +/- problems, I like to fold the int values to one side and negate as needed. The folding to one side (- or +) simplifies overflow detection as only a single side needs testing
I prefer folding to the negative side as there are more negatives, than positives. (With 32-bit int, really didn't make any difference for this problem.)
As code forms the reversed value, test if the following r * 10 + least_digit may overflow before doing it.
An int only recursive solution to reverse an int. Overflow returns 0.
#include <limits.h>
#include <stdio.h>
static int reverse_recurse(int i, int r) {
if (i) {
int least_digit = i % 10;
if (r <= INT_MIN / 10 && (r < INT_MIN / 10 || least_digit < INT_MIN % 10)) {
return 1; /// Overflow indication
}
r = reverse_recurse(i / 10, r * 10 + least_digit);
}
return r;
}
// Reverse an int, overflow returns 0
int reverse_int(int i) {
// Proceed with negative values, they have more range than + side
int r = reverse_recurse(i > 0 ? -i : i, 0);
if (r > 0) {
return 0;
}
if (i > 0) {
if (r < -INT_MAX) {
return 0;
}
r = -r;
}
return r;
}
Test
int main(void) {
int t[] = {0, 1, 42, 1234567890, 1234567892, INT_MAX, INT_MIN};
for (unsigned i = 0; i < sizeof t / sizeof t[0]; i++) {
printf("%11d %11d\n", t[i], reverse_int(t[i]));
if (t[i] != INT_MIN) {
printf("%11d %11d\n", -t[i], reverse_int(-t[i]));
}
}
}
Output
0 0
0 0
1 1
-1 -1
42 24
-42 -24
1234567890 987654321
-1234567890 -987654321
1234567892 0
-1234567892 0
2147483647 0
-2147483647 0
-2147483648 0
You could add a second parameter:
int reverseRec(int x, int reversed)
{
if(x == 0)
{
return reversed;
}
else
{
return reverseRec(x/10, reversed * 10 + x%10);
}
}
And call the function passing the 0 for the second parameter. If you want negative numbers you can check the sign before and pass the absolute value to this function.
In trying to learn C programming I programed this question and get some correct results and some incorrect. I don't see the reason for the difference.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h> // requires adding link to math -lm as in: gcc b.c -lm -o q11
int ReverseInt(int startValue, int decimalPlace)
{
if(decimalPlace == 0) // if done returns value
{
return startValue;
}
int temp = startValue % 10; // gets units digit
int newStart = (startValue -temp)/10; // computes new starting value after removing one digit
int newDecimal = decimalPlace -1;
int value = temp*pow(10,decimalPlace);
return value + ReverseInt(newStart,newDecimal); // calls itself recursively until done
}
int main()
{
int x, decimalP, startValue;
printf("Input number to be reversed \n Please note number must be less than 214748364 :");
scanf("%d", &x);
if (x > 214748364)
{
printf("Input number to be reversed \n Please note number must be less than 214748364 :");
scanf("%d", &x);
}
decimalP = round(log10(x)); // computes the number of powers of 10 - 0 being units etc.
startValue = ReverseInt(x, decimalP); // calls function with number to be reversed and powers of 10
printf("\n reverse of %d is %d \n", x, startValue);
}
Output is: reverse of 1234 is 4321 but then reverse of 4321 is 12340
It's late and nothing better does not come into my mind. No float calculations. Of course, integer has to be big enough to accommodate the result. Otherwise it is an UB.
int rev(int x, int partial, int *max)
{
int result;
if(x / partial < 10 && (int)(x / partial) > -10)
{
*max = partial;
return abs(x % 10) * partial;
}
result = rev(x, partial * 10, max) + abs(((x / (int)(*max / partial)) % 10) * partial);
return result;
}
int reverse(int x)
{
int max;
return rev(x, 1, &max) * ((x < 0) ? -1 : 1);
}
int main(void){
printf("%d", reverse(-456789));
}
https://godbolt.org/z/M1eezf
unsigned rev(unsigned x, unsigned partial, unsigned *max)
{
unsigned result;
if(x / partial < 10)
{
*max = partial;
return (x % 10) * partial;
}
result = rev(x, partial * 10, max) + (x / (*max / partial) % 10) * partial;
return result;
}
unsigned reverse(unsigned x)
{
unsigned max;
return rev(x, 1, &max);
}
int main(void){
printf("%u", reverse(123456));
}
when using long long to store the result all possible integers can be reversed
long long rev(int x, long long partial, long long *max)
{
long long result;
if(x / partial < 10 && (int)(x / partial) > -10)
{
*max = partial;
return abs(x % 10) * partial;
}
result = rev(x, partial * 10, max) + abs(((x / (int)(*max / partial)) % 10) * partial);
return result;
}
long long reverse(int x)
{
long long max;
return rev(x, 1, &max) * ((x < 0) ? -1 : 1);
}
int main(void){
printf("%d reversed %lld\n", INT_MIN, reverse(INT_MIN));
printf("%d reversed %lld\n", INT_MAX, reverse(INT_MAX));
}
https://godbolt.org/z/KMfbxz
I am assuming by reversing an integer you mean turning 129 to 921 or 120 to 21.
You need an initial method to initialize your recursive function.
Your recursive function must figure out how many decimal places your integer uses. This can be found by using log base 10 with the value and then converting the result to a integer.
log10 (103) approx. 2.04 => 2
Modulus the initial value by 10 to get the ones place and store it in a variable called temp
Subtract the ones place from the initial value and store that in a variable called newStart.
divide this value by 10
Subtract one from the decimal place and store in another variable called newDecimal.
Return the ones place times 10 to the power of the decimal place and add it to the function where the initial value is newStart and the decimalPlace is newDecimal.
#include <stdio.h>
#include <math.h>
int ReverseInt(int startValue, int decimalPlace);
int main()
{
int i = -54;
int positive = i < 0? i*-1 : i;
double d = log10(positive);
int output = ReverseInt(positive,(int)d);
int correctedOutput = i < 0? output*-1 : output;
printf("%d \n",correctedOutput);
return 0;
}
int ReverseInt(int startValue, int decimalPlace)
{
if(decimalPlace == 0)
{
return startValue;
}
int temp = startValue % 10;
int newStart = (startValue -temp)/10;
int newDecimal = decimalPlace -1;
int value = temp*pow(10,decimalPlace);
return value + ReverseInt(newStart,newDecimal);
}
I have a function print_number.
The function checks if in front of the number there exists '-', then it reverse the number and takes every digit and prints it. The algorithm works pretty good but if i give -2.147.483.648 ( which should be the bottom limit of an integer ) it pritns -0 and i don't know why.
#include<stdio.h>
void print_char(char character)
{
printf("%c",character);
}
void print_number(int nr)
{
int reverse=0;
if (nr < 0)
{
print_char('-');
nr *= -1;
}
while(nr > 9)
{
reverse = reverse * 10 + nr % 10;
nr = nr / 10;
}
print_char(nr + '0');
while(reverse)
{
print_char(reverse % 10 + '0');
reverse = reverse / 10;
}
}
When you are doing
if (nr < 0)
{
print_char('-');
nr *= -1;
}
It inverses negative number to the positive one.
If you will run it for -2.147.483.648, you will receive
nr = 2.147.483.648 // == binary 1 0000000000000000000000000000000
As INT is 32 BIT variable in your architecture (and at least 16 BIT variable by the spec), so '1' overflows it and so on
nr = 0 // For gcc-like C realisation
And accepting the ISO9899 spec, this behaviour of signed int overflow is realisation-specified thing and may not be predicted in common.
Use long long value if you're needing to use your program for larger values.
Something like:
#include<stdio.h>
void print_char(char character)
{
printf("%c",character);
}
void print_number(long long nr)
{
int reverse=0;
if (nr < 0)
{
print_char('-');
nr *= -1;
}
while(nr > 9)
{
reverse = reverse * 10 + nr % 10;
nr = nr / 10;
}
print_char(nr + '0');
while(reverse)
{
print_char(reverse % 10 + '0');
reverse = reverse / 10;
}
}
void main(void){
print_number(-2147483648LL);
}
And test:
> gcc test.c
> ./a.out
-2147483648
Firstly, the MAX and MIN range for an INT are -2,147,483,648 and 2,147,483,647 respectively.
Negating -2,147,483,648 means a positive value 2,147,483,648 would result in an overflow by 1 as it is out of bounds for the MAX range.
This operation will result in the same value of -2,147,483,648.
Secondly, you might encounter an overflow during the integer reversing process.
Example, reversing 2147483647 causes an overflow after the intermediate result of 746384741.
Therefore, you should handle that by throwing an exception or returning 0.
Thirdly, your loop for reversing the number is inaccurate. It should loop till while(nr != 0)
Here's the complete code.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
void reverseNumber(int);
reverseNumber(124249732);
return 0;
}
void reverseNumber(int nr)
{
printf("nr = %d\n", nr);
int reverse = 0;
bool neg = false;
if (nr < 0) {
neg = true;
nr *= -1;
}
while (nr != 0) {
int digit = nr % 10;
int result = reverse * 10 + digit;
if ((result - digit) / 10 != reverse) {
printf("ERROR\n");
exit(0);
}
reverse = result;
nr = nr / 10;
}
if(neg) {
printf("%c", '-');
}
printf("%d\n", reverse);
}
nr *= -1; is a problme when nr == INT_MIN as that is signed integer overflow. The result is undefined behavior (UB). Best to avoid.
Wider integers are not always available.
Using OP's general, approach, do not change the sign of nr until it is reduced.
void print_number(int nr) {
int reverse = 0;
if (nr < 0) {
print_char('-');
//nr *= -1;
}
while (nr/10) { // new test
reverse = reverse * 10 + nr % 10;
nr = nr / 10;
}
reverse = abs(reverse); // reverse = |reverse|
nr = abs(nr); // nr = |nr|
print_char(nr + '0');
while (reverse) {
print_char(reverse % 10 + '0');
reverse = reverse / 10;
}
}
Enter a unsigned int, reverse it and see if its' still in range, if it is, print the reverse number, if not, print your number is out of range
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main() {
unsigned int a = UINT_MAX; // 0xffff
printf("max unsigned int = %u\n\n", a);
unsigned int x = 0;
printf("please enter any unsigned int,\nit will show the reverse number if it's in range\n(enter 10 digit only)\n\n");
while (scanf("%u", &x) != EOF) {
//printf("x = %u\n", x);
// above %d will print each UINT's binary oder, ex: enter 4294967292, x = -1
// if change %u, it will print entered number, ex: enter 4294967292, x = 4294967292
unsigned int temp = x, result = 0;
int m = 0;
while (temp > 0) {
unsigned int digit = temp % 10;
if (result > 429496729) {
m++; //if reversed 9digits is already bigger 429496729,
//then 'result = result * 10 + digit', it will have over flow problem.
}
result = result * 10 + digit;
temp /= 10;
if (temp == 0) break;
}
printf("m=%d\n", m);
if (m >= 1)
printf("out of range\n");
else
printf("result is %u\n", result);
printf("\n");
}
return 0;
}
You never return the reversed number, all you return is the final (rightmost) digit.
And your function doesn't "return itself", it returns the result of calling itself, which is not the same.
Your test for overflow is incorrect because you compare the unsigned int result with a value that is larger than the range of this type, so the test always fails.
There are 2 ways to check for overflow:
taking advantage of unsigned arithmetics, you can compare is the result is smaller than the previous result.
alternately, you can compare if result is larger than UINT_MAX / 10 or if it is equal, if digit is larger than UINT_MAX % 10. This method works for all integer types, unsigned and signed.
Here is the modified code:
#include <stdio.h>
#include <limits.h>
int main(void) {
unsigned int x;
printf("max unsigned int = %u\n\n", UINT_MAX);
printf("please enter any unsigned int,\n"
"it will show the reverse number if it is in range\n"
"(enter 10 digit only)\n\n");
while (scanf("%u", &x) == 1) {
unsigned int temp = x, result = 0;
int overflow = 0;
while (temp > 0) {
unsigned int digit = temp % 10;
if (result > UINT_MAX / 10
|| (result == UINT_MAX / 10 && digit > UINT_MAX % 10)) {
overflow++; // the result will not fit
break;
}
result = result * 10 + digit;
temp /= 10;
}
if (overflow)
printf("out of range for unsigned int type\n\n");
else
printf("result is %u\n\n", result);
}
return 0;
}
Thanks for your answer, much appreciated!
1. Regarding to "compare if result is larger than UINT_MAX / 10 or if it is equal, if digit is larger than UINT_MAX % 10. This method works for all integer types, unsigned and signed."
Is (result == UINT_MAX / 10 && digit > UINT_MAX % 10)) necessary?
I assume input below digits
(reminder: only enter digit within UINT_MAX)
unsigned int 4294967295 (10digit), reverse will be 592769492(4) /out
range
unsigned int 4294967294 (10digit), reverse will be 492769492(4)
/out range
unsigned int 4227694924 (10digit), reverse will be 429496722(4) / in
range
unsigned int 927694924(9digit), reverse will be 429496729 / in
range
the closest input is 3927694924 i can think of, and it will fit (result == UINT_MAX / 10 && digit > UINT_MAX % 10)) / in range
However, I've done the same for signed int, please see the code at below, but im not sure how to apply your method of signed int:
#include <stdio.h>
#include <limits.h>
int main(void) {
int x;
printf("max int = %d\n", INT_MAX);
printf("min int = %d\n\n", INT_MIN);
printf("please enter any integer within -2,147,483,648 ~ 2,147,483,647,\n"
"it will show the reverse number if it is in range\n"
"(enter 10 digit or less)\n\n");
while (scanf("%d", &x) == 1) {
int temp = x, result = 0;
int overflow = 0;
while (temp >= INT_MIN || temp <= INT_MAX) {
int digit = temp % 10;
printf("temp is %u\n", temp);
printf("result is %u\n", result);
if (result > INT_MAX / 10 || (result == INT_MAX / 10 && digit > INT_MAX % 10)) {
overflow++; // the result will not fit
break;
}
if (result < INT_MIN / 10 || (result == INT_MIN / 10 && digit > INT_MIN % 10)) {
overflow++; // the result will not fit
break;
}
result = result * 10 + digit;
temp /= 10;
if(temp == 0) break;
}
if (overflow)
printf("out of range for int type\n\n");
else
printf("result is %d\n\n", result);
}
return 0;
}