0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LeetCode - 326. Power of Three

Last updated at Posted at 2020-02-22

問題

326. Power of Three - 与えられた整数が3の累乗数かどうかを判定せよ

解答

ループまわすのと、再帰と考えてみる

ループ


# @param {Integer} n
# @return {Boolean}
def is_power_of_three(n)
  if n == 1
    true
  elsif n < 3
    false
  else
    while n != 3
      if n % 3 == 0
        n = n / 3
      else
        return false
        exit
      end
    end
    true
  end
end
  • 3 の累乗数ならば、商が 3 になるまで 3 で割りづつけても、あまりは 0 であるはず
  • X の 0 乗は 1 なので true

スコア


Runtime: 64 ms, faster than 85.71% of Ruby online submissions for Power of Three.
Memory Usage: 9.2 MB, less than 100.00% of Ruby online submissions for Power of Three.

再帰


# @param {Integer} n
# @return {Boolean}
def is_power_of_three(n, power_value = 1)
  #puts "n=#{n} power_value=#{power_value}"
  return true if n == power_value
  return false if n < power_value
  is_power_of_three(n, power_value * 3)
end
  • これは、LeetCodeのサイトにあった ぱっと思いつかなかったが、すばらしい解ですね
  • 3 の累乗数を小さいものから作っていき、どこかで nと 一致すれば n は 3 の累乗数、通り越してしまったら累乗数ではない

スコア

Runtime: 92 ms, faster than 20.00% of Ruby online submissions for Power of Three.
Memory Usage: 9.3 MB, less than 100.00% of Ruby online submissions for Power of Three.

きれいだけど速くはないんですね

テスト


require 'minitest/autorun'
require '../326-power-of-three.rb'

class DoTest < Minitest::Test

  def test_1
    assert_equal true, is_power_of_three(27)
  end

  def test_2
    assert_equal false, is_power_of_three(0)
  end

  def test_3
    assert_equal true, is_power_of_three(9)
  end

  def test_4
    assert_equal false, is_power_of_three(45)
  end

  def test_5
    assert_equal true, is_power_of_three(1)
  end

  def test_6
    assert_equal false, is_power_of_three(19684)
  end

  def test_7
    assert_equal false, is_power_of_three(-3)
  end

  def test_8
    assert_equal false, is_power_of_three(6)
  end

end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?