如何编写在base 2中添加2个数字的算法? [英] How do I write algorithm adding 2 number in base 2?
问题描述
该算法约为2个数字,例如a,b在基数2中,并将它们添加到基数2而不转换为基数10
我花了数小时就可以了而且还剩下一天
我尝试过的事情:
这是我尝试过的最后一件事:
c = 0
i = 1
ans = 0
(**) c = c + a%10 + b%10
如果c> = 2
{
ans = ans + 10 ^ i +(c-2)* 10 ^(i-1)
c = 1 >
}
其他
{
ans = ans + c * 10 ^(i-1)
c = 0
}
a = a / 10
b = b / 10
i = i + 1
如果a = 0&& b = 0&& c = 0
go (!!)
else
go (**)
(!!)结束
the algorithm is about 2 numbers for example a,b in base 2 and adding them in base 2 without converting to base 10
and i've spend hours on it and there's only one day left
What I have tried:
this is the last thing i've tried:
c=0
i=1
ans=0
(**)c=c+a%10+b%10
if c>=2
{
ans=ans+10^i+(c-2)*10^(i-1)
c=1
}
else
{
ans=ans+c*10^(i-1)
c=0
}
a=a/10
b=b/10
i=i+1
if a=0 && b=0 && c=0
go (!!)
else
go(**)
(!!)end
推荐答案
按照处理器的方式(按类别)进行 - 使用一位加法器。
依次从a和b中提取每一位,并将它们与进位一起添加,以生成带有更新进位的单位解决方案:
Do it the way processors do (sort of) - use a one-bit adder.
Extract each bit from a and b in turn, and add them together with a carry bit to produce a single bit solution with an updated carry:
Inputs: Result:
A B C C X
0 0 0 0 0
0 1 0 0 1
1 0 0 0 1
1 1 0 1 0
0 0 1 0 1
0 1 1 1 0
1 0 1 1 0
1 1 1 1 1
使用它来循环处理所有位,然后就完成了。
Use that it a loop to process all the bits, and you are done.
这篇关于如何编写在base 2中添加2个数字的算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!