[ create a new paste ] login | about

Link: http://codepad.org/h0Ic9Vh6    [ raw code | output | fork ]

kabhwan - Ruby, pasted on Apr 8:
# C/C++ 로 배우는 자료구조론 연습문제 6.28

class Stack

  def initialize(size)
    @top = -1

    @memory = []
    @stack_size = size
  end

  def is_full
    return @top >= (@stack_size - 1)
  end

  def is_empty
    return @top == -1
  end

  def push(data)
    return nil if is_full

    @top += 1

    @memory[@top] = data
  end

  def pop
    return nil if is_empty

    data = @memory[@top]

    @top -= 1

    return data
  end

end

def convert_to_binary_recur(num_dec)
  return num_dec.to_s if num_dec < 2
  
  mod = num_dec % 2
  return convert_to_binary_recur(num_dec / 2) + mod.to_s    
end

def convert_to_binary_using_stack(num_dec)
  binary_str = ""
  stack = Stack.new(10)

  until num_dec < 2
    mod = num_dec % 2
    stack.push(mod)

    num_dec = num_dec / 2
  end

  stack.push num_dec if num_dec > 0

  until stack.is_empty
    mod = stack.pop
    binary_str = binary_str + mod.to_s
  end
  
  return binary_str
end

puts convert_to_binary_recur(26)
puts convert_to_binary_using_stack(26)


Output:
1
2
11010
11010


Create a new paste based on this one


Comments: