Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2x.
Follow up: Could you solve it without loops/recursion?
Solution
We can solve this problem with a simple while loop.
However, it’s important to be mindful of the differences in division behavior among different programming languages. In languages like C# and Java, integer division will result in an integer, so we multiply the dividend by 1.0 to ensure it becomes a floating-point number.
And now, let’s consider the range of ‘power of two’ numbers.
First, power of two numbers are always non-negative, meaning they are greater than or equal to zero.
Second, in the context of this problem, we don’t need to consider fractional or non-integer values (e.g., 21/2). We are only interested in whole numbers that are powers of two, such as 2, 4, 8, 16, 32, etc.
C# Solution
⚠️Solution1 – using loop
public class Solution {
public bool IsPowerOfTwo(int n) {
if(n<0){
return false;
}
double nn = n*1.0;
while(nn>=2)
{
nn/=2;
}
return nn == 1.0;
}
}
In the code, we use a ‘while’ loop to repeatedly divide the number ‘nn’ by 2.
This loop continues until ‘nn’ becomes less than 2. At this point, we know that if ‘nn’ is exactly 1.0, it means the original number ‘n’ is a power of two.
This is because 20 equals 1, and any further division would result in a number less than 1, indicating that it’s not a power of two.
In the follow-up of the problem, it asks if we can solve it without using loops/recursion.
Now, we can examine the binary representations to identify powers of two and find their common properties.
20=1 (binary: 1)
21=2 (binary: 10)
22=4 (binary: 100)
23=8 (binary: 1000)
24=16 (binary: 10000)
25=32 (binary: 100000)
26=64 (binary: 1000000)
27=128 (binary: 10000000)
28=256 (binary: 100000000)
29=512 (binary: 1000000000)
210=1024 (binary: 10000000000)
We can observe that the powers of 2 have a pattern where they start with 1 followed by zeros.
⭐Solution2 – binary
public class Solution {
public bool IsPowerOfTwo(int n) {
if(n<0){
return false;
}
string binaryStr = Convert.ToString(n, 2);
return binaryStr.LastIndexOf('1') == 0;
}
}
To determine if a number is a power of 2, we examine its binary representation. Since powers of 2 start with ‘1’ followed by zeros, we utilize the LastIndexOf method to check if the position of the ‘1’ is at index 0.
Java Solution
⚠️Solution1
class Solution {
public boolean isPowerOfTwo(int n) {
if(n<0){
return false;
}
double nn = n*1.0;
while(nn>=2)
{
nn/=2;
}
return nn == 1.0;
}
}
⭐Solution2 – binary
class Solution {
public boolean isPowerOfTwo(int n) {
if (n < 0) {
return false;
}
String binaryStr = Integer.toBinaryString(n);
return binaryStr.lastIndexOf('1') == 0;
}
}
You can refer to the explanation provided above for the C# version.
Python3 Solution
⚠️Solution1
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if(n<0):
return False
while(n>=2):
n/=2
return n == 1
⭐Solution2 – binary
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if(n<=0):
return False
s = "{0:b}".format(n)
return s.rindex("1")==0
JavaScript Solution
⚠️Solution1
/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfTwo = function(n) {
if(n<0){
return false;
}
while(n>=2)
{
n/=2;
}
return n == 1;
};
Conclusion
We’ve solved this problem using a loop.
However, for the follow-up, there is certainly another solution. I’ll take some time to think about it, and I’ll update the post ASAP!
HAHA! Using binary makes it easy to solve! (updated)
🧡If my solution helps, that is my honor!
🧡You can support me by sharing my posts or clicking ads, thanks you~~
✅If you got any problem about the explanation or you need other programming language solution, please feel free to let me know !!
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"76ca984753"};
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"76ca984753","uagb_grid_ajax_nonce":"046b2ea66b"};
( function() {
let elements = document.querySelectorAll( '.uagb-post-grid.uagb-block-613bccac .uagb-post-pagination-wrap a' );
elements.forEach(function(element) {
element.addEventListener("click", function(event){
event.preventDefault();
const link = event.target.getAttribute('href').match( /\/page\/\d+\// )?.[0] || '';
const regex = /\d+/; // regular expression to match a number at the end of the string
const match = link.match( regex ) ? link.match( regex )[0] : 1; // match the regular expression with the link
const pageNumber = parseInt( match ); // extract the number and parse it to an integer
window.UAGBPostGrid._callAjax({"btnBorderStyle":"none","overallBorderColor":"","block_id":"613bccac","categories":"62","displayPostExcerpt":false,"displayPostComment":false,"displayPostImage":false,"imgSize":"medium","linkBox":false,"orderBy":"rand","excludeCurrentPost":true,"postPagination":true,"pageLimit":0,"imageRatio":"2-3","imgEqualHeight":true,"btnBorderLink":true,"btnBorderRadiusLink":true,"overallBorderLink":true,"overallBorderRadiusLink":true,"inheritFromTheme":true,"postType":"post","postDisplaytext":"No post found!","taxonomyType":"category","postsToShow":6,"enableOffset":false,"postsOffset":0,"displayPostDate":true,"excerptLength":15,"displayPostAuthor":false,"displayPostTitle":true,"displayPostTaxonomy":false,"hideTaxonomyIcon":true,"taxStyle":"default","displayPostTaxonomyAboveTitle":"withMeta","imgPosition":"top","bgOverlayColor":"#000000","overlayOpacity":"50","displayPostLink":true,"newTab":false,"ctaText":"Read More","inheritFromThemeBtn":false,"buttonType":"primary","btnHPadding":"","btnVPadding":"","columns":3,"tcolumns":2,"mcolumns":1,"align":"left","width":"wide","order":"desc","rowGap":20,"rowGapTablet":20,"rowGapMobile":20,"columnGap":20,"bgType":"color","bgColor":"#f6f6f6","titleTag":"h4","titleFontSize":"","titleFontSizeType":"px","titleFontFamily":"","titleLineHeightType":"em","titleLoadGoogleFonts":false,"metaColor":"","highlightedTextColor":"#fff","highlightedTextBgColor":"#3182ce","metaFontSize":"","metaFontSizeType":"px","metaFontFamily":"","metaLineHeightType":"em","metaLoadGoogleFonts":false,"excerptColor":"","excerptFontSize":"","excerptFontSizeType":"px","excerptFontFamily":"","excerptLineHeightType":"em","excerptLoadGoogleFonts":false,"displayPostContentRadio":"excerpt","ctaBgType":"color","ctaBgHType":"color","ctaFontSize":"","ctaFontSizeType":"px","ctaFontFamily":"","ctaLineHeightType":"em","ctaLoadGoogleFonts":false,"paddingTop":20,"paddingBottom":20,"paddingRight":20,"paddingLeft":20,"contentPadding":20,"ctaBottomSpace":0,"ctaBottomSpaceTablet":0,"ctaBottomSpaceMobile":0,"imageBottomSpace":15,"titleBottomSpace":15,"metaBottomSpace":15,"excerptBottomSpace":25,"contentPaddingUnit":"px","rowGapUnit":"px","columnGapUnit":"px","excerptBottomSpaceUnit":"px","paginationSpacingUnit":"px","imageBottomSpaceUnit":"px","titleBottomSpaceUnit":"px","metaBottomSpaceUnit":"px","ctaBottomSpaceUnit":"px","paddingBtnUnit":"px","mobilePaddingBtnUnit":"px","tabletPaddingBtnUnit":"px","paddingUnit":"px","mobilePaddingUnit":"px","tabletPaddingUnit":"px","isPreview":false,"taxDivider":", ","titleLetterSpacing":"","titleLetterSpacingType":"px","metaLetterSpacing":"","metaLetterSpacingType":"px","ctaLetterSpacing":"","ctaLetterSpacingType":"px","excerptLetterSpacing":"","excerptLetterSpacingType":"px","useSeparateBoxShadows":true,"boxShadowColor":"#00000070","boxShadowHOffset":0,"boxShadowVOffset":0,"boxShadowBlur":"","boxShadowSpread":"","boxShadowPosition":"outset","boxShadowColorHover":"","boxShadowHOffsetHover":0,"boxShadowVOffsetHover":0,"boxShadowBlurHover":"","boxShadowSpreadHover":"","boxShadowPositionHover":"outset","borderWidth":"","borderStyle":"none","borderColor":"","borderRadius":"","blockName":"post-grid","equalHeight":true,"paginationBgActiveColor":"#e4e4e4","paginationActiveColor":"#333333","paginationBgColor":"#e4e4e4","paginationColor":"#777777","paginationMarkup":"","paginationLayout":"filled","paginationBorderColor":"#888686","paginationBorderSize":1,"paginationSpacing":20,"paginationAlignment":"left","paginationPrevText":"\u00ab Previous","paginationNextText":"Next \u00bb","layoutConfig":[["uagb\/post-image"],["uagb\/post-taxonomy"],["uagb\/post-title"],["uagb\/post-meta"],["uagb\/post-excerpt"],["uagb\/post-button"]],"post_type":"grid","equalHeightInlineButtons":false,"paginationType":"ajax","isLeftToRightLayout":false,"wrapperTopPadding":"","wrapperRightPadding":"","wrapperLeftPadding":"","wrapperBottomPadding":"","wrapperTopPaddingTablet":"","wrapperRightPaddingTablet":"","wrapperLeftPaddingTablet":"","wrapperBottomPaddingTablet":"","wrapperTopPaddingMobile":"","wrapperRightPaddingMobile":"","wrapperLeftPaddingMobile":"","wrapperBottomPaddingMobile":"","wrapperPaddingUnit":"px","wrapperPaddingUnitTablet":"px","wrapperPaddingUnitMobile":"px","wrapperPaddingLink":false,"wrapperAlign":"row","wrapperAlignPosition":"center","extended_widget_opts_block":{},"extended_widget_opts":{},"extended_widget_opts_state":"","extended_widget_opts_clientid":"","dateUpdated":""}, pageNumber, '613bccac');
});
});
} )();
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};