# Is that number a Two Bit Number™️?

Let's start by defining a Two Bit Number™️:

• It is a positive integer
• When expressed as a binary string it has exactly 2 true bits OR
• When expressed as a decimal number, it has exactly 2 of the numeral one, and all other numerals are zero.

Or as a sentence

A Two Bit Number™️ is a number which contains exactly 2 of the numeral 1 and no other numerals besides 0, when expressed as a decimal string or a binary number.

So here area all the Two Bit Numbers™️ between 0 and 256

Dec  Bin       Type
3    00000011  Binary
5    00000101  Binary
6    00000110  Binary
9    00001001  Binary
10   00001010  Binary
11   00001011  Decimal
12   00001100  Binary
17   00010001  Binary
18   00010010  Binary
20   00010100  Binary
24   00011000  Binary
33   00100001  Binary
34   00100010  Binary
36   00100100  Binary
40   00101000  Binary
48   00110000  Binary
65   01000001  Binary
66   01000010  Binary
68   01000100  Binary
72   01001000  Binary
80   01010000  Binary
96   01100000  Binary
101  01100101  Decimal
110  01101110  Decimal
129  10000001  Binary
130  10000010  Binary
132  10000100  Binary
136  10001000  Binary
144  10010000  Binary
160  10100000  Binary
192  11000000  Binary


The challenge:

• Write some code which accepts a number and outputs true or false (or some indicator of true or false) if it is a Two Bit Number™️.
• Input will always be an integer, but it may not always be positive.
• It can be in any language you like.
• It's code golf, so the fewest bytes wins.

## Test Cases

Binary Two Bit Numbers™️:

• 3
• 9
• 18
• 192
• 288
• 520
• 524304

Decimal Two Bit Numbers™️:

• 11
• 101
• 1001
• 1010
• 1100
• 1000001
• 1100000000
• 1000000010

Non Two Bit Numbers™️:

• 0
• 1
• 112 (any numerals over 1 prevent it being a binary
• 200
• 649
• -1
• -3

Fun fact: I was not able to find any DecimalBinary Two Bit Numbers™️ checking up to about 14 billion, and I have a hypothesis that such a number does not exist, but I have no mathematical proof. I'd be interested to hear if you can think of one.

• I've sketched out a somewhat clumsy proof that no DB2B number exists. Not sure if it makes sense though – Jo King Sep 30 at 14:07
• @JoKing How do you get from 10^x+10^y = 2^x+2^b to 5^x = 2^b/10^y? It looks like you may have incorrectly treated the former expression as though it said * instead of +, and then divided both sides by 2^x*10^y. – Lynn Sep 30 at 14:43
• Input will always be an integer, but it may not always be positive. How are negative numbers encoded? With a minus in front? With a 1 in front? Using two's complement? – Stef Sep 30 at 15:35
• The existence of DecimalBinary Two Bit Numbers™️ is a fascinating nerd-snipe problem! – Sisyphus Oct 1 at 0:38
• You have -1 as not a Two Bit number (it would be in 2-s complement), you have -3 as not a Two Bit number (it would be with a minus sign character prepended). You do not have -11 as an example (again would be with a minus sign). I can only imagine that your rule is to convert to a base representation using digits in $[-b+1..0]$ e.g. -123 base 10 is [-1,-2,-3] $= -1 \times 10^2 + -2 \times 10^1 + -1 \times 10^0$. Without a spec it seems we can say all negative numbers are not Two Bit Numbers, so why, are there example ones and why do we even need to handle them? – Jonathan Allan Oct 1 at 2:39

# Python 3, 6862 48 bytes

-6 bytes thanks to xnor!
-14 bytes thanks to Jitse!

lambda n:' 11 'in f' {n:b} {n} '.replace('0','')


Try it online!

• @user your 51 bytes returns false for all valid binaries entries – Kaddath Sep 30 at 13:47
• Its looks like you can cut the (n>0)* because any negative values will fail the test due to their minus sign. – xnor Sep 30 at 21:18
• you can replace s.replace('0','')=='11' with s.count('1')==2 – Turksarama Oct 1 at 5:39
• @Turksarama this would fail for inputs like 121. The s.replace('0','')=='11' makes sure there are no other digits. – ovs Oct 1 at 6:50
• 52 bytes – Jitse Oct 1 at 7:22

# JavaScript (ES6), 38 bytes

Returns 0 for true, or a non-zero integer for false.

n=>(g=n=>!(n&=n-1)|n&n-1)(n)*g('0b'+n)


Try it online!

### How?

The helper function g removes the two least significant bits set in n by computing n & (n - 1) twice. If we get 0 the first time, it means that n has at most one bit set, which is not enough. If we don't get 0 the second time, it means that n has more than 2 bits set, which is too much.

For the decimal test, we invoke g with '0b' + n to parse it as a binary value. If n is negative, this gives something such as '0b-10100', which is NaN'ish and fails as expected.

# JavaScript (ES6),  40  39 bytes

Returns a Boolean value telling whether the input is not a Two Bit Number.

n=>[n,'0b'+n].every(n=>!(n&=n-1)|n&n-1)


Try it online!

f n=or[b^x+b^y==n|b<-[2,10],x<-[0..n],y<-[x+1..n]]


Try it online!

Brute force search.

## Alternative 50 bytes

b!0=0
b!x=rem x b^3+b!quot x b
f n=2!n==2||10!n==2


b!x computes a base-b “cubed digit sum” of x. For example, 10!123 = $$\1^3+2^3+3^3\$$ = 36.

We check if either of 2!n or 10!n equals 2.

quot is necessary to support negative input. It rounds toward zero, whereas div rounds down, meaning div (-1) 10 == (-1), causing an infinite loop.

# APL (Dyalog Extended), 18 bytes

2∊+/↑(*3)2 10⊤¨0⌈⎕


Try it online!

Jo King's 18 byte solution.

# APL (Dyalog Extended), 20 21 20 26 25 bytes

{<⍵:2∊+/↑(⊂×⍨⍎¨⍕⍵)⍪⊂⊤⍵⋄0}


Try it online!

+1 byte after correcting the answer(ovs).

-1 byte after ovs's suggestion.(yay!)

+7 bytes after properly accepting negative test cases.

Inspired from the J solution.

## Explanation

{⍵>0:2∊+/↑(⊂2*⍨⍎¨⍕⍵)⍪⊂⊤⍵⋄0}
⍵>0:                       If number is positive
⊤⍵    Decode number to binary
×⍨⍎¨⍕⍵          square each digit
↑ ⊂        ⍪⊂      join into two rows
+/                   sum each row
2∊                     is two present in it?
⋄0 otherwise return 0

• I think there might be another problem. For some reason I couldn't test it, but I think this returns 1 for negative inputs like ¯5, so you need an ⍵>0 check (like the J solution). – ovs Sep 30 at 14:37
• it errors on negative inputs like ¯5 due to ⍕ and ⍎ getting the digits. just needs a conditional. – Razetime Sep 30 at 16:27
• Doesn't this fail to output 0 on negative numbers? – Adám Sep 30 at 19:58
• now it does. @Adám – Razetime Oct 1 at 3:13
• Your score is a mountain range series. – Dominic van Essen Oct 1 at 6:24

# 05AB1E, 8 7 bytes

b‚€{11å


Explanation:

b        # Convert the (implicit) input-integer to a binary string
‚       # Pair it together with the (implicit) input-integer
€{     # Sort the digits in each string
11å  # And check if this pair contains an 11 (which is truthy for "011","0011",etc.)
# (after which the result is output implicitly)


# R, 504948 46 bytes

Edit: -1 byte, and then -1 more byte, and then -2 more bytes, thanks to Robin Ryder

gsub(0,'',n<-scan())!=11&sum(n%/%2^(0:n)%%2)-2


Try it online!

Tests for decimal 2bit numbers using text manipulation to remove '0' digits and check whether the result is not '11', and then tests for binary 2bit numbers by calculating the binary digits and checking if they do not sum to 2. Returns FALSE for 2bit numbers and TRUE for non-2bit numbers.
It seems a bit clunky to do two different kinds of tests for essentially the same feature, but somehow comes-out quite short...

• Nice! You can save a byte by putting n<-scan() in the gsub call. – Robin Ryder Oct 1 at 13:33
• Thanks a lot! How did I not realize that? – Dominic van Essen Oct 1 at 13:57
• 48 bytes by inverting the output. – Robin Ryder Oct 1 at 16:28
• @RobinRyder that's neat. I suppose we can always use - instead of != for numeric comparisons, and so probably instead of == if (like here) there's a way to 'flip' the output. Nice trick! – Dominic van Essen Oct 1 at 16:38
• Precisely. That also works e.g. in if statements. – Robin Ryder Oct 1 at 19:14

# J, 25 bytes

0&<*10&#.inv+&(2=1#.*~)#:


Try it online!

### How it works

0&<*10&#.inv+&(2=1#.*.~)#:
0&<*                       input is a positive number
10&#.inv               list of digits base 10
#: list of digits base 2
+&(        )   OR the result of both …
*.~    square each digit (x>=2 will be larger than 2)
1#.       sum
2=          is equal to two


If there is a DecimalBinary number, the + as OR could result in 2, thus needing one byte more for +..

# Brachylog, 9 bytes

ℕ{ḃc|}o11


Try it online!

Somewhat embarrassed I didn't think to translate other solutions' sort-based approaches earlier...

A more fun solution:

# Brachylog, 10 bytes

ℕ{|ẹ~ḃ}ḃ+2


Try it online!

ℕ             The input is a whole number (necessary to exclude -3 etc.),
{|   }       which either unchanged or
ẹ          with its decimal digits
~ḃ        interpreted as binary (impossible if any ≥ 2),
ḃ      has binary digits
+2    that sum to 2.


# Brachylog, 12 11 bytes

ℕ{ḃ|ẹ}<ᵛ²+2


Try it online!

-1 byte thanks to xash

ℕ              The input is a whole number,
{ | }         and either
ḃ            its binary digits
ẹ          or its decimal digits
<ᵛ²      are all less than 2
+2    and sum to 2.

• 11 bytes – xash Sep 30 at 13:27
• Was sort of considering something like that, but never thought to superscript ᵛ--thanks! – Unrelated String Sep 30 at 13:34
• Why does + not work on numbers and requires ẹ? – Kroppeb Sep 30 at 17:05

# Japt, 9 bytes

There's gotta be a way to shave at least one more byte off this.

ìÍ¶BªB¥¢ñ

ìÍ¶BªB¥¢ñ     :Implicit input of integer U
ì             :Convert to digit array
Í            :Sort (and implicitly convert back to integer)
¶           :Test for strict equality with
B          :11
ª         :Logical OR with
B¥       :Test 11 for equality with
¢      :Convert U to binary string
ñ     :Sort


# Raku, 25 bytes

{$_|.base(2)~~/^10*10*$/}


Try it online!

Checks if the input or the base 2 of the input matches the regex ^10*10*$ # Charcoal, 21 13 bytes №⟦⁻θ0⁻⍘Ｎ²0⟧11  Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. - for a two bit number, nothing if not. Port of @Kaddath's PHP answer. Explanation:  θ Input as a string ⁻ 0 Remove zeros Ｎ Input as a number ⍘ ² Convert to base 2 ⁻ 0 Remove zeros ⟦ ⟧ Make into a list № 11 Count occurances of literal string 11  # Python 3, 67 bytes lambda n:n>2in{g(n,2),g(n,10)} g=lambda x,b:x and(x%b)**2+g(x//b,b)  Try it online! Port of my Haskell answer. (I took the test harness from ovs's Python answer. Thanks!) # R, 71 64 bytes -7 bytes thanks to Dominic van Essen +=function(n,k)sum((n%/%k^(0:n)%%k)^2)-2 n=scan();n<0|n+2&n+10  Try it online! Output is reversed: gives FALSE if the input is a Two Bit Number, and TRUE if it is not. The helper function + converts an integer to a vector of digits in base k (we need k=2 and k=10). Then sum the square of these digits. This sum is equal to 2 exactly for a Two Bit Number. Will fail due to memory limits for large input, in which case you can use 0:log2(n) instead of 0:n and || instead of |: Try it online!. • This seems to invert true and false... Not sure if that's usually allowed with IO rules. – AJFaraday Sep 30 at 14:13 • @AJFaraday Yes, that is what I meant by "output is reversed". I took the challenge spec of "some indicator of true or false" as meaning that any 2 consistent values (here false and true) would be OK, but if that doesn't suit you I can correct it at the cost of 1 or 2 bytes. – Robin Ryder Sep 30 at 14:29 • I've checked, this is typically allowed. Upvoted :) – AJFaraday Sep 30 at 14:35 • @AJFaraday This is explicitly allowed by your own rules anyway, as some indicator of true or false can definitely be false and true. – Arnauld Sep 30 at 14:53 • Actually | works now that the log2 is out! – Robin Ryder Sep 30 at 19:05 # Factor, 79 74 bytes : n ( n -- ? ) [ 10 >base ] [ >bin ] bi [ 48 swap remove "11" = ] bi@ or ;  Try it online! # Jelly, 8 bytes ,BṢ€Ḍ11e  Try it online! ## Explanation ,BṢ€Ḍ11e Main Link , Pair the integer with B Convert the integer to binary Ṣ€ Sort Each (sorts the digits of the integer implicitly) Ḍ Convert from decimal to integer 11e Is 11 in this list?  # Perl 5-lp, 35 bytes $_=grep/^10*10*$/,$_,sprintf"%b",$_  Try it online! returns 1 or 2 (if a number can be decimal and binary Two Bit number) for true, 0 for false. # Wolfram Language (Mathematica), 46 bytes !FreeQ[Tr/@(#~IntegerDigits~{10,2}^2),2]&&#>0&  Try it online! -1 byte from @att • -1 byte since infix has higher precedence than Power – att Sep 30 at 16:55 ## PCRE Regex, 100 95 bytes ^(((?(2)\2\2|.))*.)(?!\1)((?(3)\3\3|.))*.$|^(((?(5)\5{10}|.{9}))*.)(?!\4)((?(6)\6{10}|.{9}))*.$ Assume unary input (no support for negative numbers). Should work in flavors with support for conditional regex and forward-declared back-reference. The regex consists of 2 similar portions, one check for binary and the other for decimal. • The code makes use of sum of geometric series to match 2n and 10n. 1 + (1 + 2 + 22 + ... + 2n) = 2n+1 1 + 9 * (1 + 10 + 102 + ... + 10n) = 10n+1 • Then it try to decompose the number into sum of 2n + 2k (or 10n + 10k for decimal), and check that 2n != 2k Update: • Drops unused capturing group • Drops $ in (?!\1$) since it's fine if we reject 2n < 2k regex101 • I really did not expect a regex answer to this :) – AJFaraday Oct 1 at 12:51 • This inelegant regex works in ecma: ^((x)+|(x)+)(((\2+)\3+)\6{8}(?=\5$))+(?=(((\2+)\3+)\9{8}(?=\8$))*x$)\1$. Ideally the choice distinction 2 and 10 would be more subtle. – H.PWiz Oct 1 at 15:00 • @H.PWiz Post your own answer :) – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Oct 1 at 15:41 • Took me a while to figure out what the regex is about - it decomposes number n into a * (1 + 2^b) then check a = 2^k. And the capturing group 2 and 3 switches between base 2 and base 10. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Oct 1 at 16:29 • Is there any reason not to do this? – Neil Oct 3 at 1:08 # Julia, 61 bytes using a regex on the binary and decimal representation of the number x->any(match.([r"^0*10*10*$"],["$x",bitstring(x)]).!=nothing)  Try it online! # Julia, 69 bytes by sorting the caracters x->any(endswith.(join.(sort.(collect.(["0$x",bitstring(x)]))),"011"))


Try it online!

• Nice first post! – Redwolf Programs Oct 2 at 16:20

# Ruby 2.7, 44 bytes

->n{[2,10].any?{n.to_s(_1).tr(?0,'')=='11'}}


Explanation:

->n{                      # a lambda with one argument
[2,10].any?{          # Return true if for either of 2 or 10...
n.to_s(_1)          # input in that base
.tr(?0,'')          # after removing all 0-s
=='11'              # is exactly '11'
}
}


## Equivalent in ruby < 2.7, 46 bytes

->n{[2,10].any?{|b|n.to_s(b).tr(?0,'')=='11'}}


Try it out

# Retina 0.8.2, 36 bytes

^\d+
$*1¶$&
+^(1+)\1
$+0 m^10*10*$


Try it online! Link includes most test cases (the larger ones cause Retina to run out of memory). Explanation:

^\d+
$*1¶$&


If the input is non-negative, prefix it with a unary copy.

+^(1+)\1
$+0  Begin converting the unary copy to binary. At this point there are too many zeros in the result, but fortunately they are irrelevant. m^10*10*$


Match either number as being a two bit number.

# K (ngn/k), 25 24 bytes

-1 byte thanks to ngn

{("11"~($x)^$0)+2=+/2\x}


Try it online!

• "0" ---> $0 – ngn Oct 6 at 22:07 • @ngn Thank you! – Galen Ivanov Oct 7 at 0:08 # PHP, 69 67 bytes echo($f=fn($s)=>str_replace(0,'',$s)==11)($argn)|$f(decbin($argn));  Try it online! Pretty straightforward: treats each input as a string, replaces all zeroes by '' and tests if it (loosely) equals 11, or if the binary does EDIT: saved 2 bytes by using 0 instead of '0' # APL (Dyalog Extended), 19 bytes 2∊2 10(+.×⍨⊤)¨⊢×0<⊢  Try it online! Commented:  0<⊢ ⍝ Is the (right) argument greater than 0 ⊢× ⍝ Multiply this with the argument ⍝ results in 0 for negative inputs 2 10( )¨ ⍝ Call the next function with each of the bases 2 and 10 ⍝ and the non-negative number as a right argument ⊤ ⍝ Convert number to base digits +.×⍨ ⍝ The sum of squares of the digits 2∊ ⍝ Does this contain 2?  # C (gcc), 75 $$\\cdots\$$ 76 80 bytes Added 6 bytes to fix a bug. d;r;c;f(n){for(c=2,r=__builtin_popcount(n)!=2|n<0;n>0;n/=10)d=n%10,c-=d*d;r*=c;}  Try it online! Returns a falsy value if $$\n\$$ is a Two Bit Number™️ or a truthy one otherwise. • strictly speaking __builtin_popcount is a built-in function that only exists in some compilers and not a standard function – phuclv Oct 2 at 4:15 • @phuclv true, but, "For the purposes of PPCG, a programming language is defined by its implementation." codegolf.meta.stackexchange.com/a/7833/43195 – Phoenix Oct 2 at 4:40 • @phuclv As it clearly states my answer is for GCC, __builtin_popcount is a GCC builtin. – Noodle9 Oct 2 at 10:12 # Pyth, 22 16 bytes -6 bytes thanks to @FryAmTheEggman }11,v-Q\0v-.BQ\0  Try it online! • You can save some bytes by using - to remove zeros (it will automatically convert to string) and using } to test on a list rather than doing two equality comparisons. – FryAmTheEggman Oct 1 at 16:16 # Python, 79 Bytes lambda n:any(sum((ord(c)-48)**4 for c in f.format(n))==2for f in["{}","{0:b}"])  ## Explanation I format the int as both binary and decimal. For each character, I subtract the '0' character, then raise it to the power of 4. This maps '0' to 0, '1' to 1, '2' to 16, and other digits and the '-' character to numbers greater than 16. Then, I check if the summation equals 2. # Octave, 67 64 bytes @(x,p=@(b,z=dec2base(x*(x>0),b)-48)all(z<2)&sum(z)==2)p(2)|p(10)  Try it online! If in doubt, make the code more convoluted. Somehow that tends to save bytes... @(x, % Main anonymous function with 'x' as input p= % Second input 'p' with default value (no second input is given when calling function) which @(b, % consists of another anonymous function which takes base as input z= % From which it creates a second input 'z' with default value dec2base( ,b) % Which runs dec2base (convert from integer to string) using provided base x % On the input to the main anonymous function *(x>0) % Multiplied by (x>0) to return false for any negative integer passed in. -48 % And converts from a string to an array of integers (one per digit) ) all(z<2)& % Two-bit numbers must only contain 0 or 1, so need all elements in array of digits <2. sum(z)==2 % Sum all digits. Two-digit number if sum is 2 (two 1's) ) p(2))|| % Run two-bit number check in base 2 p(10) % Run two-bit number check in base 10  First attempt, @(x,p=@(z)all(z<50)&&sum(z-48)==2)x>0&&p(dec2bin(x))||p(num2str(x))  Try it online! @(x, % Main anonymous function with 'x' as input p= % Second input 'p' with default value (no second input is given when calling function) @(z) % Default value consists of another anonymous function to check if string is two-bit all(z<50)&& % Two-bit numbers must only contain '0' or '1', so need all elements in string <'2'(50). sum(z-48)==2 % Convert all characters from '0'/'1' to 0/1 and sum. Two-digit if sum is 2 (two 1's) ) x>0&& % Short-circuit to return false for any negative integer passed in. p(dec2bin(x))|| % Convert to binary string and check if two-digit, or... p(num2str(x)) % Convert to decimal string and check if two-digit  # T-SQL, 93 bytes Returns 1 for true, 0 for false DECLARE @y INT=@,@x INT=9WHILE @>0SELECT @x+=@%2,@/=2PRINT IIF(11in(@x,replace(@y,0,'')),1,0)  Try it online # Generic regex, 58 bytes ^((((1+)(?=\4$))+|^)1){2}$|^((((1+)\8{8}(?=\8$))+|^)1){2}$ Try it online! Link includes test harness written in Retina 0.8.2 although the regex itself should work in most engines. Takes input in signed unary i.e. ^-?1*$. Explanation: Given k and m we can write a specific test for a number being the sum of k distinct powers of m by repeatedly dividing by m and subtracting 1 k distinct times along the way, before we eventually reach zero:

^((((1+)\4{<m-2>}(?=\4$))+|^)1){<k>}$


where <m-2> and <k> represent substitutions for the specific values being tested (subject to trivial reductions such as \4{0} being a no-op). This works as follows:

    (1+)                                Find i such that
\4{<m-2>}                       i+(m-2)i=(m-1)i is equal to
(?=\4$) n-i, therefore i=n/m. ( )+ Divide n by m at least once ( |^) Except on the first loop ( 1){<k>} Decrement k distinct times ^$   Consume entire input


The problem then reduces to an alternation of two such tests.