Set next_additive to 0.
For every digit in number (starting at the left):
Set additive to next_additive.
If the digit is odd, set next_additive to 5, else set it to 0.
Divide the digit by two (truncating) then add additive.
Remove leading zero if necessary (if it starts with 0 but is not just 0).
举例来说,这里's a Python approach to implementing this algorithm as follows. First the support routine for checking if a string-number is odd (keep in mind this isn' t意味着是Pythonic代码,它几乎肯定是用Python做的更好的方法,但不一定能很好地映射到另一种语言):
def oddsToOne(s):
if s.endswith('1'): return 1
if s.endswith('3'): return 1
if s.endswith('5'): return 1
if s.endswith('7'): return 1
if s.endswith('9'): return 1
return 0
1 回答
如果这是一个真正的问题,那里有很多BigNum库可以提供帮助,例如MPIR库 .
如果你不能使用第三方库,它实际上需要一个复杂的BigNum库,你只需要一个操作:除以2 .
这是你如何做到的 . 从一堆空二进制数字开始 . 然后循环直到数字为“0”(是的,那仍然是一个字符串) . 如果数字的最后一位是奇数,则将1按到堆栈,否则按0.然后将数字除以2并重新启动循环 .
循环结束后(数字为“0”),一次一个地从堆栈中弹出数字并打印出来 . 你去吧
哦,是的,除以二,这是一个相当重要的难题:-)
让我们从“12345”开始吧 . 这是您在伪代码中遵循的过程 .
这可以通过一次处理实际字符串一个字符来完成 .
从
1
(从12345
开始),加法为0
,数字为奇数,因此next_additive为5
. 将1
除以2
并添加0
的加法,得到0
:02345
.下一个数字
2
,添加剂为5
,数字为偶数,因此next_additive为0
. 将2
除以2
并添加5
的加法,得到6
:06345
.下一个数字
3
,加法为0
,数字为奇数,因此next_additive为5
. 将3
除以2
并添加0
的加法,得到1
:06145
.下一个数字
4
,添加剂为5
,数字为偶数,因此next_additive为0
. 将4
除以2
并添加5
的加法,得到7
:06175
.下一个数字
5
,加法为0
,数字为奇数,因此next_additive为5
. 将5
除以2
并添加0
的加法,得到2
:06172
.剥离前导零:
6172
. 由于您截断了结果,因此忽略下一个添加剂 .你有它:
12345 / 2 = 6172
.举例来说,这里's a Python approach to implementing this algorithm as follows. First the support routine for checking if a string-number is odd (keep in mind this isn' t意味着是Pythonic代码,它几乎肯定是用Python做的更好的方法,但不一定能很好地映射到另一种语言):
然后是另一个将字符串数除以2的支持例程:
最后,一些实际代码从十进制字符串生成二进制字符串:
请注意,如果您想实际使用它来填充实际位(而不是生成一串位),那么更改
if
和else
子句中发生的事情是一件简单的事情 .如上所述,它可能不是你能想到的最有效或最漂亮的Python代码,但它正在继续):
因为这适用于数字的字符串表示,所以没有任意数字限制,例如64位整数的大小 . 一些示例值(为了便于阅读,稍微重新格式化为32位数字块):