Skip to content

Instantly share code, notes, and snippets.

@chhanganivarun
Last active May 13, 2019 09:54
Show Gist options
  • Save chhanganivarun/55a25e66e5e80ed509d0cdc188c46c01 to your computer and use it in GitHub Desktop.
Save chhanganivarun/55a25e66e5e80ed509d0cdc188c46c01 to your computer and use it in GitHub Desktop.
increment and decrement without basic math operators
#include<stdio.h>
int increment(int *c)
{
int x=1;
while((*c)&x)
{
*c^=x;
x<<=1;
}
*c^=x;
return *c;
}
int decrement(int *c)
{
int x=1;
while(!((*c)&x)&&x!=0)
{
*c^=x;
x<<=1;
}
*c^=x;
return *c;
}
int main()
{
for(int i = -2;i<=16;)
printf("%d\n",increment(&i));
for(int i=16;i>=-2;)
printf("%d\n",decrement(&i));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment