These are some really simple yet helpful tricks you can use.
1. Using push_back()
instead of concatenate string.
If you are using string concatenation if you want to add a char at the
end of a string then use push_back()
function instead because
for (char c = 'a'; c <= 'z'; c++)
{
str = str + c;
}
The above code makes a copy of str
everytime you concatenate string, so the time
complexity of this code becomes O(26)*O(str.size())
.
Time complexity of push_back()
is O(1)
.
for (char c = 'a'; c <= 'z'; c++)
{
str.push_back(c)
}
So the overall time complexity of above code bacomes O(26)
.
2. Using num&1
instead of num%2!=0
.
Even if both returns the same output
if (num & 1)
{
cout << "Number is odd";
}
the above code looks more readable than
if (num % 2 != 0)
{
cout << "Number is odd";
}
The logic behind the num&1
is that the least significant bit (LSB) of every odd number is always 1.
For e.g. Binary of 1, 3, 5, 7 is
1 = 001,
3 = 011,
5 = 101,
7 = 111
as you can see the last bit (least significant bit) of every odd binary number is 1.
And then doing AND with 1 (binary is 001) gives the result 1 or True
if the number is odd.
3. Using ternary operators than if-else.
We all started with if-else and to be honest it is much more readable than ternary operators, but if-else also takes more line of code.
For e.g.
if (num & 1)
{
cout << "Number is odd";
}
else
{
cout << "Number is even";
}
as you can see if-else takes much more space than using ternary operator,
here we have done the same operation in only one line.
cout << ((num & 1) ? "Number is odd" : "Number is even");
Thank you for reading all the way through. Please let me know if the article (or the code) can be improved in any way in the comments down below.