Sum of Digits

June 22, 2007

Following is a way to sum the digits into a single digit.

 

e.g. let we have to sum the digits of number 234578.

2 + 3 + 4 + 5 + 7 + 8 = 29; sum it again until a single digit.

2 + 9 = 11; sum it again until a single digit.

1 + 1 = 2 ; it is final sum of digits.

so sum of digits of number 234578 is 2.

 

Here is the code for sum of digits:

 

For any given positive integers n;

if (n != 0) {

if (n % 9 == 0) {

return 9;

}

return n % 9;

}

return 0;

 

Piece of code will always return sum of digits.

Power of Two

April 5, 2007

One best way to find whether an integer is power of two or not :

For any given positive integer n;

return n & n - 1;

Expression will return:

zero; if n is power of 2,

non-zero; otherwise.

Integers Comparison

March 29, 2007

Best way to compare equality of two integer variables without using comparison operator is:

For any given integers a and b;

return a ^ b;

Expression will return:

zero; if a and b are equal,

non-zero; otherwise.

Swapping Integer Variables

March 22, 2007

Two integer variables can be swapped in many different ways.

One of the best way to swap is given below.

For any given integers a and b;

a ^= b ^= a ^= b;

An Alternative Multiplication Operation

March 21, 2007

Raheel Shahzad who was my senior at Palmchip and the best Pakistani programmer I have seen so far on acm site, has asked how to make faster the following expression.

For any given integer n; n = n * 7;

I come up with the follwoing solution.

n = (n << 3) - n;

Limitation: n can overflow.


Follow

Get every new post delivered to your Inbox.