Decimal to Binary Conversion Using Stack

Share with your friends!

මේ කියන්න යන්නේ මොකද්ද කියලා දැනටමත් දන්නවා ඇතිනේ.input එක විදියට දෙන decimal, එහෙම නැත්තං 10 පාදයේ සංඛ්‍යාව stack එකක් use කරලා binary කරගන්න එක තමයි කරන්න හදන්නේ.සාමාන්‍යයෙන් binary කරද්දී කරන්නේ දෙකෙන් බෙදලා ශේෂය විදියට එන අගයන් අරගන්න එක.මුලින්ම බලමු අපිට මේ දේ කරන්න ඕන වෙන මුලික දේ මොකද්ද කියලා.උදාහරණයක් විදියට 22 කියන සංඛ්‍යාව ගමු.

22/2 =11 (0)

11/2 = 5(1)

5/2 = 2(1)

2(2) = (1)(0)

මෙතැනදී වරහන් වල තියෙන්නේ ලැබෙන ශේෂය.ඒ වගේම අන්තිම සංඛ්‍යා දෙකම binary value එකට අයිති වෙනවා.ලැබෙන output බැලුවම ලැබෙන පිළිවෙල වෙන්නේ > 0,1,1,0,1 නමුත් 2210 වෙන්නේ 101102 කියන අගය, මේ reverse කිරීමට තමයි stack එක use කරන්නේ.stack එකේදී අන්තිමට PUSH කරන element එක මුලින්ම POP කරන්නේ.මේ තියෙන්නේ ඒ code එක.

class stack:

  def __init__(self):
    self.stk = []

  def push(self, ele):
    self.stk.append(ele)

  def pop(self):
    return(self.stk.pop())

  def len(self):
    return(len(self.stk))

  def peek(self):
    return(self.stk[len(self.stk)-1])

  def isEmpty(self):
    if(len(self.stk) == 0):
      return(True)
    else:
      return(False)

v = ""
s = stack()
a = int(input("Enter Decimal Value >>"))

while(a>0):
  digit = a%2
  s.push(int(digit))
  a = (a - digit)/2

while(not s.isEmpty()):
  v += str(s.pop())

print(v)

Share with your friends!

Leave A Comment

shares