79
\$\begingroup\$

Me thinks there aren't enough easy questions on here that beginners can attempt!

The challenge: Given a random input string of 1's and 0's such as:

10101110101010010100010001010110101001010

Write the shortest code that outputs the bit-wise inverse like so:

01010001010101101011101110101001010110101
\$\endgroup\$

128 Answers 128

0
\$\begingroup\$

Java, 55 bytes

a->a.replace('0','2').replace('1','0').replace('2','1')

This is a java.util.function.UnaryFunction<String>.

\$\endgroup\$
0
\$\begingroup\$

Turtlèd, 24 bytes (non-competing)

' !-[*+.(1'0r)(0'1r)_]' 

[note trailing space]

beating the non golf langs, in a task this language is not really designed for :)

Explanation

'[space]                      write space over initial square
  !                           take input into string variable
   -                          decrement the string pointer (used when writing char from string)
    [*               ]        while current cell is not *
      +.                      increment string pointer, write pointed char from string
        (1'0r)                if cell is 1, write 0, move right
              (0'1r)          if cell is 0, write 1, move right
                    _         EOF checker: if end of string var, write *, else [space]
                      '[space]write space on cell (asterisk must be here)
          [implicit]     remove trailing and leading spaces and newlines, print grid.
\$\endgroup\$
0
\$\begingroup\$

Python 3 - 59 41 bytes

( -18 bytes thanks to @Mego)

lambda s:''.join(str(1-int(c))for c in s)
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! This solution is valid in both Python 2 and Python 3. There's quite a few improvements you can make, though. 1) By using a lambda function instead of a named function, you can omit the return statement: lambda s:''.join('1'if c=='0'else'0'for c in list(s)). 2) Strings are iterable, so you can replace list(s) with simply s). 3) Using boolean arithmetic on integer values is shorter: str(1-int(c)) instead of '1'if c=='0'else'0'. If you're willing to restrict your answer to Python 2 only, `1-int(c)` is even shorter. \$\endgroup\$ – Mego Sep 20 '16 at 4:43
  • \$\begingroup\$ How'd you know I'm new here! Thanks for your suggestions, editing my answer now! I'd rather keep it compatible to both py3 and py2 though. \$\endgroup\$ – Biarity Sep 20 '16 at 11:10
  • 1
    \$\begingroup\$ I know you're new here because I found your answer in the review queue for answers posted by new users. \$\endgroup\$ – Mego Sep 20 '16 at 11:11
0
\$\begingroup\$

Reticular, 13 bytes

iSBl[:0Eo]~*;

Try it online! Obviously non-competing, as language postdates question.

Explanation

iSBl[:0Eo]~*;
i              take one line of input
 S             convert string to array of chars
  B            merge array with stack
   l           push the length
    [    ]~*   active the inside (length) times
     :0        push the string "0"
       E       check for equality
        o      output
            ;  terminate program
\$\endgroup\$
0
\$\begingroup\$

Python 3, 57 bytes

print(''.join(['0' if i=='1' else '1' for i in input()]))
\$\endgroup\$
0
\$\begingroup\$

Java, 97 bytes

Inspired by a comment from 2 years ago @hdante ...

Golfed version:

String d(String s){String r="";for(int i=0;i<s.length();)r(s.charAt(i++)=='0')?"1":"0";return r;}

Ungolfed version:

String d(String s)
{
    String r = "";
    for (int i = 0; i < s.length();)
        r += (s.charAt(i++) == '0') ? "1" : "0";
    return r;
}

Nothing too fancy ...

\$\endgroup\$
0
\$\begingroup\$

C#, 47 44 bytes

as an anonymous function takes a string and returns a string

s=>s.Aggregate("",(a,b)=>a+(b>'0'?'0':'1'));

or as an anonymous function takes a string and prints the inverted, also in 47 bytes

s=>{foreach(var c in s)Write(c=='0'?'1':'0');};

\$\endgroup\$
0
\$\begingroup\$

Befunge 98, 13 bytes

#@~1+:'1`2*-,

Increments each character, and substracts 2 if the result is greater than '1' (using a multiply instead of a conditional, i.e. using 2 * <greater than '1'>).

Commented version:

v / Skip the next byte
  |
  |/ End
  ||
  ||/ getc, reflect IP on EOF
  |||
  |||/ push 1
  ||||
  ||||/ add
  |||||
  |||||/ duplicate TOS
  ||||||
  ||||||/ character literal
  |||||||
  |||||||/ push '1'
  ||||||||
  ||||||||/ greater than
  |||||||||
  |||||||||/ push 2
  ||||||||||
  ||||||||||/ multiply
  |||||||||||
  |||||||||||/ substract
  ||||||||||||
  ||||||||||||/ putc
  |||||||||||||
> #@~1+:'1`2*-,
\$\endgroup\$
0
\$\begingroup\$

Binary-Encoded Golfical, 31 bytes

Noncompeting, language postdates the question.

This encoding can be converted back to Golfical's standard graphical format using the encoder/decoder provided in the Golfical github repo, or run directly by using the -x flag.

Hex dump of binary encoding:

00 80 03 00 30 14 14 0C 01 14 14 1B 14 1A 16 14
14 26 14 14 25 1B 14 00 30 00 31 17 1C 1C 1D

Original image:

enter image description here

Scaled up 45x:

enter image description here

\$\endgroup\$
0
\$\begingroup\$

Lithp, 61 bytes + 3 for -v1 flag

#S::((replace S (regex "\\d" "g") (js-bridge #X::((^ X 1)))))

Requires the -v1 flag to run.js, as js-bridge is not part of the standard library yet.

Exploits the JavaScript's String.replace function by passing a bridge function, allowing Lithp code to handle the replacement.

Usage:

(
    (def i #S::((replace S (regex "\\d" "g") (js-bridge #N::((^ N 1))))))
    (print (i "01010101111000"))
)
\$\endgroup\$
0
\$\begingroup\$

Python 3, 39 bytes

Taking input from stdin and printing to stdout:

for c in input():print(1-int(c),end="")
\$\endgroup\$
0
\$\begingroup\$

Logicode, 9 bytes

out ~ainp

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Java, 39 bytes

s->{for(int i=s.length;i-->0;)s[i]^=1;}

Testing

import java.util.Arrays;
import java.util.function.Consumer;

public class Pcg30361 {
  public static void main(String[] args) {
    Consumer<char[]> f = s->{for(int i=s.length;i-->0;)s[i]^=1;};

    char[] s = "10101110101010010100010001010110101001010".toCharArray();

    char[] expected = "01010001010101101011101110101001010110101".toCharArray();

    f.accept(s);
    System.out.println(Arrays.equals(s, expected));

  }
}
\$\endgroup\$
0
\$\begingroup\$

Python 3.5, 54 Bytes

print(''.join('1'if a=='0' else '0' for a in input()))

Much longer now ;-; (but it depends how you interpret the Q, invert can mean "reverse" as well as "opposite")

\$\endgroup\$
  • \$\begingroup\$ This is problematic for two reasons. 1) doesn't do what the challenge asks this reverses a binary string instead of inverting it, 2) it assumes input from a predefined variable which is not considered a valid form of input, relevant meta. \$\endgroup\$ – Sriotchilism O'Zaic Feb 7 '17 at 19:12
  • \$\begingroup\$ "Invert" has more than one possible interpretation, so it's a simple mistake. Other than that, your right, changes'll be applied later \$\endgroup\$ – Zachary Smith Feb 7 '17 at 19:28
0
\$\begingroup\$

Python 2.7, 69 bytes

Full Program:

b=raw_input();a=''
for i in b:
    if i=='1':a+='0'
    else:a+='1'
print a

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Its not clear from the specifications but this probably doesn't do what the question wants. It does not work on the one test case provided. \$\endgroup\$ – Sriotchilism O'Zaic Jun 11 '17 at 18:11
  • \$\begingroup\$ @WheatWizard- My bad. I didn't understand the question. Correcting it. \$\endgroup\$ – Koishore Roy Jun 12 '17 at 7:40
  • \$\begingroup\$ I wouldn't say its your bad, the question is extremely unclear, only providing a test case. \$\endgroup\$ – Sriotchilism O'Zaic Jun 12 '17 at 13:19
0
\$\begingroup\$

q/kdb+, 8 bytes

Solution:

"01""0"=

Example:

q)"01""0"="1010101100010011"
"0101010011101100"

Explanation:

Same vein as the J answers, use a boolean list to index into an array of "01"

/ return list of bools where list = "0" (thus inverted)
q)"0"="1010101100010011"
0101010011101100b
/ index into array of "01" at indexes 0 or 1
q)"01" 0101010011101100b
"0101010011101100"
\$\endgroup\$
0
\$\begingroup\$

C++, 39 bytes

void f(string s){for(v:s)cout<<(v<49);}
\$\endgroup\$
0
\$\begingroup\$

Befunge-98, 12 bytes

'0:~\-!+:,j@

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Check, 27 bytes

Non-competing as language postdates the question.

   :,r>#v
#d=!pd)##.:+&:R-?

Check is my new esolang. It uses a combination of 2D and 1D semantics. Stack manipulation is done in 1D, while control flow is done in 2D.

This program assumes that the input bits were passed as a command-line argument.

\$\endgroup\$
0
\$\begingroup\$

Aceto, 7 bytes non-competing

-i
1,p>

Push 1, read a character and cast it to an int, subtract, print, go back to the start.

Non-competing because the challenge predates the language.

\$\endgroup\$
0
\$\begingroup\$

Chip, 6 bytes

A~ae*f

Try it online!

A       Take bit 0x01 of input
 ~      Invert it
  a     Set bit 0x01 of output to that value
    *   Provide a constant 1 value to neighbors
   e f  Set bits 0x10 and 0x20 to 1

So, in English, this prints '0' if the low bit of input is on, and '1' if the low bit is off.

(Chip is a 2D language, which is why the * sends a signal both left and right. It sends the same up and down too. a and e don't interact, so no whitespace is needed there.)

We can handle raw binary data too, in 31 bytes:

A~a B~b C~c D~d E~e F~f G~g H~h

This simply inverts all bits.

\$\endgroup\$
0
\$\begingroup\$

Jq 1.5, 29 bytes

./""|map("\(1-tonumber)")|add

Expanded

  ./""                   # split into array of one character strings
| map("\(1-tonumber)")   # invert each element
| add                    # join array back into a single string

Try it online!

\$\endgroup\$
0
\$\begingroup\$

J-uby, 14 bytes

~:tr&'01'&'10'

equivalent to lambda { |x| x.tr("01","10")}; literally replaces 1 with 0 and 0 with 1.

\$\endgroup\$
0
\$\begingroup\$

SQL 2017, 35 bytes

The TRANSLATE keyword is only available starting in SQL 2017 (is the "non-competing" rule still a thing?), and replaces all instances of characters from the second string with the corresponding character in the third.

SELECT TRANSLATE(a,'01','10')FROM t

Input is via pre-existing table t, per our input standards.

The triple replace for older SQL versions is nearly twice as long (65 bytes):

SELECT REPLACE(REPLACE(REPLACE(a,'0','2'),'1','0'),'2','1')FROM t
\$\endgroup\$
0
\$\begingroup\$

RProgN 2, 5 bytes

³n¬w;

Try it online!

\$\endgroup\$
0
\$\begingroup\$

ARBLE, 23 bytes

join(a|"."|#floor(1-a))

Try it online!

\$\endgroup\$
0
\$\begingroup\$

OML, 10 bytes

1(j1^oee)L

Try it online!

Explanation

1(j1^oee)L
1(    ee)    while stdin is not empty
  j          take a character of input
   1^        xor it with 1
     o       and output it
        L    clear the stack (stack is displayed implicitly otherwise)
\$\endgroup\$
0
\$\begingroup\$

R, 49 bytes,

bitwXor(strtoi(unlist(strsplit(scan(,""),""))),1)

Not the shortest answer, but eh !

Here, we :

  • take as input the sequence as a character string scan(,""),
  • split it into its digits strsplit(x, ""), creating a list (an R object),
  • flatten the list unlist(x), creating a vector (another R object).

The items in the vector are converted to integers strtoi, on which the XOR logical operation is applied bitwXor, with respect to 1.

Here we're taking advantage of R's recycling. Both elements of the fonction bitwXor are vectors, but have different length. The function reuse the shortest vector to apply the operation to each element of the longest vector.


Briefly, XOR (⊕) table of truth is :

1 ⊕ 1 = 0
1 ⊕ 0 = 1
0 ⊕ 1 = 1
0 ⊕ 0 = 0

\$\endgroup\$
0
\$\begingroup\$

Excel VBA, 15 Bytes

y=StrReverse(x)

Assuming that x is a String Input, StrReverse Function can be used and the output is y As String. (Credit: Grant Peters)

A code to test the result:

Sub test()
    Dim x As String, y As String
    x = "10101110101010010100010001010110101001010"
    y = StrReverse(x)
    Debug.Print y
    'Output: 01010010101101010001000101001010101110101
End Sub
\$\endgroup\$
0
\$\begingroup\$

Braingolf, 12 bytes

i{#0-}n&,{_}

Try it online!

Explanation

i{#0-}n&,{_}
i             Read line from STDIN, convert each char to ordinal and push to stack
 {...}        Foreach, runs on each item in stack
  #0-         Subtract 48 from each ordinal
      n       Negate, all truthy values become 0, all falsey values become 1
       &,     Flip entire stack
         {_}  Print each item

Or...

Braingolf, 7 bytes [kinda double non-competing]

dn&,{_}

Try it online!

Kinda non-competing because braingolf cannot accept integer input from command-line arguments, it will always implicitly convert it to an integer if the input is only digits.

Explanation

dn&,{_}  Implicit input from command-line args
d        Split number into digits
 n       Negate, all truthy values become 0, all falsey values become 1
  &,     Flip entire stack
    {_}  Print each item
\$\endgroup\$

protected by Community Jan 11 at 5:12

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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