✒️
Leetcode
  • Leetcode
  • Ruby
    • 1. Two Sum
    • 7. Reverse Integer
    • 9. Palindrome Number
    • 13. Roman to Integer
    • 14. Longest Common Prefix
    • 20. Valid Parentheses
    • 21. Merge Two Sorted Lists
    • 26. Remove Duplicates from Sorted Array
    • 27. Remove Element
    • 28. Implement strStr()
    • 35. Search Insert Position
    • 38. Count and Say
    • 53. Maximum Subarray
    • 58. Length of Last Word
    • 66. Plus One
    • 67. Add Binary
    • 69. Sqrt(x)
    • 70. Climbing Stairs
    • 83. Remove Duplicates from Sorted List
    • 88. Merge Sorted Array
    • 100. Same Tree
    • 101. Symmetric Tree
    • 104. Maximum Depth of Binary Tree
    • 121. Best Time to Buy and Sell Stock
    • 122. Best Time to Buy and Sell Stock II
    • 125. Valid Palindrome
    • 136. Single Number
    • 141. Linked List Cycle
    • 155. Min Stack
    • 160. Intersection of Two Linked Lists
    • 169. Majority Element
    • 191. Number of 1 Bits
    • 198. House Robber
    • 203. Remove Linked List Elements
    • 205. Isomorphic Strings
    • 206. Reverse Linked List
    • 217. Contains Duplicate
    • 226. Invert Binary Tree
    • 231. Power of Two
    • 234. Palindrome Linked List
    • 263. Ugly Number
    • 283. Move Zeroes
    • 292. Nim Game
    • 344. Reverse String
    • 350. Intersection of Two Arrays II
    • 371. Sum of Two Integers
    • 387. First Unique Character in a String
    • 404. Sum of Left Leaves
    • 401. Binary Watch
    • 448. Find All Numbers Disappeared in an Array
    • 922. Sort Array By Parity II
    • 1051. Height Checker
    • 1380. Lucky Numbers in a Matrix
  • C#
    • 1. Two Sum
    • 7. Reverse Integer
    • 9. Palindrome Number
    • 13. Roman to Integer
    • 14. Longest Common Prefix
    • 20. Valid Parentheses
    • 21. Merge Two Sorted Lists
    • 26. Remove Duplicates from Sorted Array
    • 27. Remove Element
    • 28. Implement strStr()
    • 35. Search Insert Position
    • 38. Count and Say
    • 53. Maximum Subarray
    • 58. Length of Last Word
    • 191. Number of 1 Bits
    • 231. Power of Two
    • 401. Binary Watch
    • 1114. Print in Order
Powered by GitBook
On this page

Was this helpful?

  1. Ruby

231. Power of Two

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.

Example 1:

Input: n = 1
Output: true
Explanation: 20 = 1

Example 2:

Input: n = 16
Output: true
Explanation: 24 = 16

Example 3:

Input: n = 3
Output: false

Example 4:

Input: n = 4
Output: true

Example 5:

Input: n = 5
Output: false

Constraints:

  • -231 <= n <= 231 - 1

Follow up: Could you solve it without loops/recursion?

# @param {Integer} n
# @return {Boolean}

def is_power_of_two(n)
  return false if n <= 0
  return true if n == 1
  n.to_s(2).count('1') == 1 ? true : false
end
Previous226. Invert Binary TreeNext234. Palindrome Linked List

Last updated 4 years ago

Was this helpful?