Home > Beyond, CodinGame, Java, snippets > Unary encoded for 7-bit ASCII

Unary encoded for 7-bit ASCII

November 17, 2015 Leave a comment Go to comments

Chuck Norris challenge in codingame.com

import java.util.*;
import java.io.*;
import java.math.*;

/**
 * unary encoded
 * @author grekz.wordpress.com
 **/
class Bytes {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String MESSAGE = in.nextLine();
        StringBuilder binary = new StringBuilder(), result = new StringBuilder();
        
        for (byte b : MESSAGE.getBytes()) {
            int val = b << 1;
            for (int i = 0; i < 7; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
        }
        //grekz.wordpress.com
        char current = '2';
        for (int i = 0; i < binary.length(); i++) {
            char c = binary.charAt(i);
            if (current != c) {
                current = c;
                result.append(" ").append(current == '1' ? "0" : "00")
                        .append(" ");
            }
            result.append("0");
        }
        System.out.println(result.toString().trim());
        in.close();
    }
}
Categories: Beyond, CodinGame, Java, snippets
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: