Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to know about what is the use of that (index & 0x01) in the code?
if(((arr[index] >= 0) && (!(index & 0x01)))
|| ((arr[index] < 0) && (index & 0x01)))
{
outofplace = index;
}
A number is odd if and only if its last digit is odd, regardless of the base. So if we want to know the number's oddity, it's enough to check if the last bit is set.
index & 0x01
will be 1 if and only if index is odd.
If we have to deduce a general rule, we can say that for any non-negative number x,
x % y == (x & (y - 1))
provided that y is a positive power of 2.
This is a common hack in competitive coding. It is used because the competitive programmers think that bit-wise AND works faster than modulo.
In modern compilers, there is no performance difference at all. Read this thread.
There is no special reason in writing it as 0x01 instead of 1. Both compile to give the same assembly! Almost everyone (who uses this hack),= uses 1, because we have to type 3 characters extra in 0x01. :P
Here in this case, index & 0x1 is equivalent to index % 2 which is simply a condition to check if the number is odd. (Array indexes in C++ are always positive, unless you are going out of bound.)
As the other answers pointed out, while this is a well known pattern (see also this Q&A about that mask), it can be considered a premature optimization.
I'd like to suggest the following alternative to the posted code, which I find more readable. Your mileage may vary.
// Give a meaningful name.
constexpr auto is_odd = [] (auto x) -> bool {
return x % 2;
}
// Use it to simplify the condition.
if ( (arr[index] < 0) == is_odd(index) ) {
// Do something
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Let's say we have four variables: int a, b, c, d;. I need to check if excatly two of them are equal.
So for example: 1 1 9 5 is true, but 3 9 8 4 and 3 3 3 1 are false.
Of course writing an if statement for this would take a lot of time, won't be easily readable and it would be easy to make a mistake writing it.
What is the best way to write such statement?
There are several ways to do this.
One involves explicitly checking all the conditions. Since you have 4 variables, you only 6 conditions to check. These can easily be counted.
int n = (a == b) + (a == c) + (a == d) + (b == c) + (b == d) + (c == d);
Then check if n is 1. This works because a boolean value will be converted into an int (value 1 for true, 0 for false).
Another possibility is to store them all in a container (like a vector), sort it, then count the number of adjacent identical values.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi I used to solve string char uniqueness using map in C++. I found this solution somewhere and working fine. But I can not understand how it is working. Please some one explain.
bool isUnique(string s){
int check = 0;
for(int i=0;i<s.length();++i){
if(s[i] != ' '){
int val = s[i]-'a';
if( (check & ( 1 << val)) > 0) return false;
check = check | (1 << val);
}
}
return true;
}
It returns true if string has no repeated character excluding spaces otherwise returns false.
It is using an int as if it were a bitmap. A bitmap is certainly a better data structure for a character uniqueness test than a map. An int is a crude and questionable (in this case) substitute for a bitmap.
Assume an int has 32 bits. Those bits are allocated in this code for the first 32 characters beginning with lower case 'a'. So the upper case letters and most special characters have no bit positions and are treated as unique by this code even if they are not unique.
If you only care about uniqueness for lower case letters, and you are sure the code is only used in architectures that have at least 32 bits in an int, then this is a decent approach. Otherwise, when you want an array of bits, use some actual array of bits.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
inline int input()
{
int c;
int n = 0;
while ((c = getchar_unlocked()) >= '0' && c <= '9')
{
// n = 10 * n + (c - '0');
n = (n << 3) + ( n << 1 ) + c - '0';
}
return n;
}
Can someone explain how this way of inputting the number is working and how it is the fast way to input a number?
Compilers are generally very stupid, and have no understanding of the logic you're trying to implement. Moreover, they're often written by less-than-competent people who don't understand much of modern hardware.
The author of the code has realized this, and cleverly analyzed that 10 is the same as 8 + 2, and that 8 and 2 are both powers of two. For the flourish, he proceeded to turn the mathematics of exponentials into native, bitwise hardware instructions. This combination of mathematics and deep understanding of the hardware leads him to factor 10 * x as 8 * x + 2 * x and express the result in terms of instructions that are far more optimal than the naive "stupid multiplication" that would otherwise have taken place. Naturally, such optimizations are far beyond the reach of any kind of technology and cannot possibly be performed automatically.
The result is a vastly improved method of multiplying a number by ten.
Patent pending.
n << 3 equals n * 8
n << 1 equals n * 2
i.e. (n << 3) + ( n << 1 ) equals 10 * n
bitwise shift is faster than multiplication, though I'm not sure the whole thing should be faster.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
that displays exactly 8 (eight) Fibonacci numbers starting and ending from user-specified numbers (program’s input). For example, if a user inputs index 3 and 10, then numbers (values) F3 - F10 are shown on the screen. Erroneous user’s input (e.g. negative number) or a smaller ending number than the first, should lead to warning and automatic repetition of the input.
To give you a small hint without doing all the work for you (as this seems to be some task for school, college, or university), here's how a Fibonacci number is defined:
f(0) = 0;
f(1) = 1;
f(n) = f(n - 1) + f(n - 2);
So in C++ this could be written like this:
int fibonacci(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
This of course can be further optimized and it's not necessarily the best approach. And it also includes possible errors, that might lead to stack overflows (hey, isn't that what this site is about? :)). So try to understand the code, then try to learn and improve it. Don't just copy & paste.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to know whether there is a way in which we can print the number alphabetically i.e
123 should be printed as one two three.
The only condition is that we should not reverse the number and we should not use array.
I only know these two ways:
"Reverse the number", that is, taking the last digit and cutting it off. For each cut-off digit, one can use an array to look up the correct string.
using switch and a lot of cases
Any ideas?
for hundreds place:
int hundreds = my_num / 100 //Needs "/", NOT "%"
if(hundreds == 0)
cout << "zero";
else if(hundreds == 1)
cout << "one";
//repeat for 2-9
This process could be tweaked to do the other digits as well. It is also worth mentioning that the if/else block a) could be done with a switch/case if preferred, and b) could pretty easily be made into a separate function to avoid having to repeat the block of code over and over, I just wrote out as much as I did for clarity's sake. Note that this assumes the number you're "translating" is an integer. With integers the "/" operator will return the full quotient WITHOUT the remainder, e.g. 123 / 100 = 1, not 1.23
Not necessarily the easiest route, but you can make a function, say DigitToWord which will take a digit 0, 1, 2, ...etc to its word with a switch statement. Then I recommend using a for loop over the number, continuously dividing by 10 and taking the mod for the loop:
int num; //my number i want to print
int div = pow(10, (int)log10(num)); //find the largest power of 10 smaller than num
while(num > 0) {
int remainder = num%div;
int digit = num/div;
DigitToWord();
num = remainder;
}