Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Index the binary strings in lexicographic order, so that the empty string " " corresponds to 0, the string "0" corresponds to 1, the string "1" to 2, and so on.

I want a function that, given a natural number $n\geq0$, returns the binary string with lexicographic index $n$.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Try this function

bs[n_] := StringDrop[IntegerString[n + 1, 2], 1];

Table[{n, bs[n]}, {n, 0, 10}] // Grid
0      ""
1     "0"
2     "1"
3    "00"
4    "01"
5    "10"
6    "11"
7   "000"
8   "001"
9   "010"
10  "011"
share|improve this answer

Here's what I came up with:

encode[x_Integer?NonNegative] := StringJoin @@ ToString /@ Rest@IntegerDigits[x + 1, 2]

Test it:

In[7]:= {encode[#], #} & /@ Range[0, 6] // InputForm

Out[7]//InputForm= {{"", 0}, {"0", 1}, {"1", 2}, {"00", 3}, {"01", 4}, {"10", 5}, {"11", 6}}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.