Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class BooleanComplementer {
- /*
- Takes a string as in input and returns a string with a boolean complement
- of each digit except the last one. Example: 11101 returns 00011
- */
- public static String getComplement (String inp) {
- String ans = "";
- // loop through each character of inp
- for (int i=0; i<inp.length(); i++) {
- if (!(inp.substring(i, i+1).equals("1") || inp.substring(i, i+1).equals("0"))) {
- System.out.println ("Not a binary string!");
- ans = "-1";
- break;
- }
- if (i<inp.length()-1) {
- // when input character is 1, add 0 and vice versa
- ans += (inp.substring(i, i+1).equals("1")? "0": "1");
- } else {
- // last digit remains unchanged
- ans += inp.substring(i, i+1);
- }
- }
- return ans;
- }
- public static void main (String[] args) {
- Scanner in = new Scanner (System.in);
- String input, answer;
- System.out.print ("Enter boolean string: ");
- input = in.nextLine();
- answer = getComplement (input);
- if (!answer.equals ("-1")) {
- System.out.println ("Answer: " + answer);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement