-1

So lets say we have a function that can take either a positive or a negative integer binary string and count the amount of right shifts it takes to get to get to the leftmost significant bit

I have something like this

int shiftCount(int x){
    int count = 0;
    int temp = x;

    while((temp!=1) || (temp!=-1)){   //if negative int, terminate at first -1
        count+=1;
        temp=temp>>1;
    }

    return count;
}

This does not return what I want. It ends up in a never ending loop I assume it is because it is trying to fulfill both conditions. Is there an actual way to easily test for 2 different signed values in a while loop, or will I have to make 2 separate conditional statements, each with their own while loop?

Team. Coco
  • 85
  • 2
  • 9
  • Do you mean `&&` instead of `||`? `temp != 1 || temp != -1` means that temp is either not 1, or it is not -1, which is always true, of course. – Dietrich Epp Feb 13 '17 at 04:51
  • In times like this it can be helpful to remember [De Morgan's Laws](https://en.wikipedia.org/wiki/De_Morgan's_laws). – Dietrich Epp Feb 13 '17 at 04:52
  • Will that test both cases correctly? – Team. Coco Feb 13 '17 at 04:54
  • Ahh, i think that fixed it. Thank you. I think I disregarded the "&&" because I tried something like "temp >1 && temp<-1" earlier and it didn't work, but now i see the flawed logic in that. – Team. Coco Feb 13 '17 at 04:58

1 Answers1

1

Your or is always true. Since temp cannot be both 1 and -1, it will always be either not 1 or not -1.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278