Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Swift Warmup : power of three

Johnlin
December 13, 2016

Swift Warmup : power of three

Johnlin

December 13, 2016
Tweet

More Decks by Johnlin

Other Decks in Programming

Transcript

  1. 326. Power of Three • https://leetcode.com/problems/power-of-three/ • Given an integer,

    write a function to determine if it is a power of three. • څ㟬Ұݸ੔ᏐɼሜҰݸവᏐ൑Ꮧଞੋෆੋ 3 త࣍ํɻ
  2. • Follow up:
 Could you do it without using any

    loop / recursion? • Ճ෼୊:
 ՄҎෆ༻౸ ᫮ᅲ / ᬇ᫮ बղग़౴Ҋ䆩ʁ
  3. class Solution1 { func isPowerOfThree(_ n: Int) -> Bool {

    var nn = n while(nn%3==0 && nn>0){ nn = nn / 3 } return nn==1 } }
  4. class Solution1 { func isPowerOfThree(_ n: Int) -> Bool {

    var nn = n while(nn%3==0 && nn>0){ nn = nn / 3 } return nn==1 } } ࣌ؒෳᯑ౓: O(log(n))
 ۭؒෳᯑ౓: O(1)
 Runtime: 289 ms
  5. ԋࢉ๏ 1 • ೺Ꮠࣈ᫚੒ࡾਐҐɻ 5566 => “21122011” • 1 =>

    “1”, 3 => “10”, 9 => “100”, 27 => “1000” • 3 త࣍ํҰఆ။௕੒Ṝᒬ 100000….. ɼ໵बੋআྃ ։಄ੋ 1ɼଖଞ౎ੋ 0 • ᒾҰ༗ᔒ༗Ṝࠣಛੑब޷ɻ
  6. class Solution { func isPowerOfThree(_ n: Int) -> Bool {

    let threeBased = String(n, radix:3) guard let head = threeBased.characters.first, head == "1" else { return false } guard threeBased.characters.count > 1 else { return true } let tail = String(threeBased.characters.dropFirst()) return Int(tail) == 0 } } ᔒ༗༻౸᫮ᅲ
  7. class Solution { func isPowerOfThree(_ n: Int) -> Bool {

    let threeBased = String(n, radix:3) guard let head = threeBased.characters.first, head == "1" else { return false } guard threeBased.characters.count > 1 else { return true } let tail = String(threeBased.characters.dropFirst()) return Int(tail) == 0 } } ෆա䋯ಘ኷ຫ ࣌ؒෳᯑ౓: O(log(n))
 ۭؒෳᯑ౓: O(log(n))
 Runtime: 415 ms
  8. ԋࢉ๏ 2 • ኺവᏐతఆٛ
 func isPowerOfThree(_ n: Int) -> Bool


    ՄҎ؃ग़༌ೖᆴੋ༗্ݶతɼ໵बੋ Int.max = 9223372036854775807 • ॴҎ୞ཁፙ౸্ݶ㚎࠷େత3త࣍ํɼ࠶؃؃ n ೳෆ ೳ੔আଞɼब஌ಓ n ੋෆੋ 3 త࣍ํྃɻ

  9. class Solution { func isPowerOfThree(_ n: Int) -> Bool {

    let ms = String(Int.max, radix:3) let max3 = "1" + repeatElement("0", count: ms.characters.count-1).joined() let max3i = Int(max3, radix:3)! //4052555153018976267 return n > 0 && max3i % n == 0 } }
  10. class Solution { func isPowerOfThree(_ n: Int) -> Bool {

    return n > 0 && 4052555153018976267 % n == 0 } } ࣌ؒෳᯑ౓: O(1)
 ۭؒෳᯑ౓: O(1)
 Runtime: 255 ms
  11. Q&A