If +,-,*,/ is completely forbidden, I think at least one loop is needed.
Here is my solution:

int next8mult (int n)
{
n = (n & ~7); // clear the least 3 bit to make multiple of 8
   int r = 8;
   while(r) {                      // add 8 to n
      int r1 = (n&r) << 1;     // get carry bit
      n ^= r;                          // perform bit addition
      r = r1;                          // continue with carry.
   }
  return n;
}

On 2010-9-25 19:56, Krunal Modi wrote:
Q: Write an algorithm to compute the next multiple of 8 for a given
positive integer using bitwise operators.

Example,
(a) For the number 12, the next multiple of 8 is 16.
(b) For the number 16, the next multiple of 8 is 24.
-------------------------
I have written a code using bitwise operators...but, I am not happy
with the solution....Is there any ONE LINE solution ?
Here, is my code.
Approach: shift left till LSB is 0 (say n number of times) then, OR
with 1, finally shift right (same number of times).


#include<stdio.h>

int main(){
         int count,m,n,ans,t;


         printf("Enter any number :");
         scanf("%d",&n);

         m=8; //multiple of 8 !!
         ans=0;
         while(ans<=n){
                 t = m;
                 while(t){
                         count=0;
                         while(ans&1){
                                 count++;
                                 ans = ans>>1;
                         }
                         ans = ans|1;
                         ans = ans<<count;
                         t--;
                 }
         }

         printf("[%d]\n",ans);

         return 0;
}


--
You received this message because you are subscribed to the Google Groups "Algorithm 
Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to