Mapping two integers to one, in a unique and deterministic way

前端 未结 19 2593
不知归路
不知归路 2020-11-22 09:35

Imagine two positive integers A and B. I want to combine these two into a single integer C.

There can be no other integers D and E which combine to C. So combining

19条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 10:01

    Given positive integers A and B, let D = number of digits A has, and E=number of digits B has The result can be a concatenation of D, 0, E, 0, A, and B.

    Example: A = 300, B = 12. D = 3, E=2 result = 302030012. This takes advantage of the fact that the only number that starts with 0, is 0,

    Pro: Easy to encode, easy to decode, human readable, significant digits can be compared first, potential for compare without calculation, simple error checking.

    Cons: Size of results is an issue. But that's ok, why are we storing unbounded integers in a computer anyways.

提交回复
热议问题