Ruby on Rails function defined failed tests -
i have defined function takes in number , returns true if power of 2. otherwise, return false:
def is_power_of_two?(num) n = 0 res = false if num % 2 == 0 while 2^n <= num if 2^n == num res = true end n += 1 end end puts(n.to_s) return res end # these tests check code working. after writing # solution, should print true. puts('is_power_of_two?(1) == true: ' + (is_power_of_two?(1) == true).to_s) puts('is_power_of_two?(16) == true: ' + (is_power_of_two?(16) == true).to_s) puts('is_power_of_two?(64) == true: ' + (is_power_of_two?(64) == true).to_s) puts('is_power_of_two?(78) == false: ' + (is_power_of_two?(78) == false).to_s) puts('is_power_of_two?(0) == false: ' + (is_power_of_two?(0) == false).to_s) however, test results turn out fail 4 out of five:
0 is_power_of_two?(1) == true: false 16 is_power_of_two?(16) == true: false 64 is_power_of_two?(64) == true: false 77 is_power_of_two?(78) == false: false 0 is_power_of_two?(0) == false: true the result printed out seems match what's expected, however, tests still failed. know why happened?
if expecting ^ calculate power wrong ^ xor calculate power use **
2^2 # 0 2**2 # 4
Comments
Post a Comment