For instance, How would I be able to convert 2^60 or 12345678901234567890123456789012345678901234567890 to binary?
Basically, numbers that are too large to represent in Java.
Edit: I will be making a class that will be able to represent number that are too large. I'm just having a hard time figuring our how to convert decimal to binary.
Edit2: And also, I am not allowed to use BigDecimal, BigInteger, or any other library, sorry for not specifying earlier.
Here is a quik&dirty (very very very dirty) code:
public class BigDec2Bin {
public static int[] string2arrayReversed( String s )
{
char a[] = s.toCharArray();
int b[] = new int[ s.length() ];
for( int i = 0; i < a.length; i++ )
{
b[a.length-1-i] = a[i] - 48;
}
return b;
}
// adds two binary numbers represented as strings
public static String add( String s1, String s2 )
{
String result = "", stmp;
int[] a1, a2;
int ctmp, mark = 0;
// a1 should be the longer one
a1 = string2arrayReversed( ( s1.length() > s2.length() ? s1 : s2 ) );
a2 = string2arrayReversed( ( s1.length() < s2.length() ? s1 : s2 ) );
for( int i = 0; i < a1.length; i++ )
{
ctmp = a1[i] + ( i < a2.length ? a2[i] : 0 ) + mark;
switch( ctmp )
{
default:
case 0:
stmp = "0";
mark = 0;
break;
case 1:
stmp = "1";
mark = 0;
break;
case 2:
stmp = "0";
mark = 1;
break;
case 3:
stmp = "1";
mark = 1;
break;
}
result = stmp + result;
}
if( mark > 0 ) { result = "1" + result; }
return result;
}
public static String dec2bin( String s )
{
String result = "";
for( int i = 0; i < s.length() ; i++ )
{
result = add( result + "0", result + "000" );
result = add( result, Integer.toBinaryString( s.charAt(i) - 48 ) );
}
return result;
}
public static void main( String[] args )
{
String dec = "12345"; // should be 11000000111001
System.out.println( "dec2bin( " + dec + " ) = " + dec2bin( dec ) );
dec = "12345678901234567890123456789012345678901234567890";
System.out.println( "dec2bin( " + dec + " ) = " + dec2bin( dec ) );
}
}
Output:
dec2bin( 12345 ) = 011000000111001
dec2bin(
12345678901234567890123456789012345678901234567890
) =
10000111001001111111011000110110100110101010111110000011110010100001010100000010011001110100011110101111100011000111111100011001011011001110001111110000101011010010
My main idea is to use always strings.
add -method adds two binary numbers which are represented as strings
dec2bin -method is where the magic happens.
Allow me to explain:
result = add( result + "0", result + "000" );
is a calculation to multiply any given number by 10.
Multiplying a binary number by 10 is the same as adding the number with shifts:
x*10 <=> x<<1 + x<<3
result = add( result, Integer.toBinaryString( s.charAt(i) - 48 ) );
just adds a the next digit (from left to right) on the result string
Basicly what I'm doing is for example with 1234:
0*10 + 1 = 1
1*10 + 2 = 12
12*10 + 3 = 123
123*10 + 4 = 1234
but only in binary (represented as strings).
I hope i could help and sorry for my bad english.
Try this:
new BigDecimal("12345678901234567890123456789012345678901234567890").toString(2);
Edit:
For making a big-number class, you may want to have a look at my post about this a week ago. Ah, the question was by you, never mind.
The conversion between different number systems in principle is a repeated "division, remainder, multiply, add" operation. Let's look at an example:
We want to convert 123 from decimal to a base 3 number. What do we do?
Take the remainder modulo 3 - prepend this digit to the result.
Divide by 3.
If the number is bigger than 0, continue with this number at step 1
So it looks like this:
123 % 3 == 0. ==> The last digit is 0.
123 / 3 == 41.
41 % 3 == 2 ==> The second last digit is 2.
41 / 3 == 13
13 % 3 == 1 ==> The third digit is 1.
13 / 3 == 4
4 % 3 == 1 ==> The fourth digit is 1 again.
4 / 3 == 1
1 % 3 == 1 ==> The fifth digit is 1.
So, we have 11120 as the result.
The problem is that for this you need to have already some kind of division by 3 in decimal format, which is usually not the case if you don't implement your number in a decimal-based format (like I did in the answer to your last question linked above).
But it works for converting from your internal number format to any external format.
So, let's look at how we would do the inverse calculation, from 11120 (base 3) to its decimal equivalent. (Base 3 is here the placeholder for an arbitrary radix, Base 10 the placeholder for your internal radix.) In principle, this number can be written as this:
1 * 3^4 + 1 * 3^3 + 1*3^2 + 2*3^1 + 0*3^0
A better way (faster to calculate) is this:
((((1 * 3) + 1 )*3 + 1 )*3 + 2)*3 + 0
1
3
4
12
13
39
41
123
123
(This is known as Horner scheme, normally used for calculating values of polynomials.)
You can implement this in the number scheme you are implementing, if you know how to represent the input radix (and the digits) in your target system.
(I just added such a calculation to my DecimalBigInt class, but you may want to do the calculations directly in your internal data structure instead of creating a new object (or even two) of your BigNumber class for every decimal digit to be input.)
What about this approach:
result = 0;
for each digit in the decimal number, from left to right
result = result * 10 + digit;
return result;
So we need a way to represent an arbitrarily large binary number, and implement multiplication by 10 and addition of small numbers.
The most straightforward way to represent an arbitrarily large binary number is an array of its binary digits. You can then apply the algorithms for addition and multiplication your learned in elementary school, except that digits will "overflow" when they exceed 1 rather than 9. For example:
1010 * 1100111
----------------
11001110
+ 1100111000
----------------
10000000110
Pew: thanks, that works for some numbers. The number 6123456789012 however doesn't work, but here is the fix:
// a1 should be the longer one
a1 = string2arrayReversed( ( s1.length() >= s2.length() ? s1 : s2 ) ); //GREATER EQUAL
If you only work with integers, use BigInteger.toByteArray.
If not, unfortunately BigDecimal doesn't have that method. But I suppose you can always (in both cases) just ASCII encode the string representation of the number, if the binary form is just meant for transfer and not calculation anywhere.
there is a fast program to get the binary representation of a huge decimal.
This programm is indeed fast, it takes only 20ms to deal with a decimal with 3000digits, eg:string(3000,'2')+'12345'. because of the pursuit of efficiency, it is not very readable. you can modify it yourself to make it easier to understand.
inline string remove_pre_zero(const string& a)
{
auto t = a.find_first_not_of('\0', 0);
if (t == a.npos)
return string("0");
else
return a.substr(t);
}
string convert_to_bin(const string& _s)
{
const static string str[] = { "0", "1" };
string s(_s.size(), '0');
string binary;
binary.reserve(_s.size()*3);
int i = 0;
for (const auto& c : _s)
s[i++] = (c - '0');
while (s!="0")//simulate divide by 2
{
int t = 0, old_t = 0;
for (auto& ch : s)
{
t = ((old_t * 10 + ch) & 1);
ch = (ch + old_t * 10) >>1;
old_t = t;
}
binary += str[t];
if (s[0] == 0)
s = remove_pre_zero(s);
}
return string(binary.rbegin(), binary.rend());
}
Related
System.out.print("Enter an integer: ");
int number = input.nextInt();
String binary = "";
while(number != 0) {
if (number % 2 == 0) {
binary += "0" ;
} else{
binary += "1" ;
}
number /= 2;
}
System.out.println(binary);
I have trouble understanding what is wrong with my code.
I saw there are solutions to this question but they didn't answer the following question that I have :
I know that to display the binary the right way I need to change these line: binary += "0"; to this line: binary = "0" + binary;
I just can't understand WHY, why when I wrote that code the output is not reversed as it should be but If I add the lines it prints the right way.
Thanks.
Your code keeps checking the modulo of 2, which is in fact the least significant bit of the number, then it divides by two to move on to the next bit (move one bit to the right). For example:
29 = 11101
^ check modulo of two,
append "1",
divide by two
14 = 1110
^ check modulo of two,
append "0",
divide by two
7 = 111
^ check modulo of two,
append "1",
divide by two
3 = 11
^ check modulo of two,
append "1",
divide by two
1 = 1
^ check modulo of two,
append "1",
divide by two
(stop)
As you can see, the algorithm appends, in order:
1
0
1
1
1
Which is in fact the reverse of the binary representation. So, in other words, you need to add these digits at the beginning of the String:
while(number != 0) {
if (number % 2 == 0) {
binary = "0" + binary;
} else {
binary = "1" + binary;
}
number /= 2;
}
You are appending the binary digits in reversed order.
The first digit that you append to the String becomes the first character of the String, which means the least significant bit becomes the most significant bit in the output String.
It should be:
String binary = "";
while (number != 0) {
if (number % 2 == 0) {
binary = "0" + binary; // the newly appended digit should be to the left of the
// previously appended digits
} else {
binary = "1" + binary;
}
number /= 2;
}
System.out.println(binary);
Take a simple example:
Let number == 2
First iteration:
number % 2 == 0
binary = "0" + binary; // "0" + "" -> "0"
number /= 2; // now number == 1
Second iteration:
number % 2 != 0
binary = "1" + binary; // "1" + "0" -> "10"
number /= 2; // now number == 0
String binary = "";
while (number != 0) {
if (number % 2 == 0) {
binary = "0" + binary;
} else {
binary = "1" + binary;
}
number /= 2;
}
System.out.println(binary);
You can add at the front of the binary String.
There is an another way to do so by using the reverse() method.
String binary = "";
while (number != 0) {
if (number % 2 == 0) {
binary += "0" ;
} else {
binary += "1" ;
}
number /= 2;
}
String reverseBinary = new StringBuffer(binary).reverse().toString();
System.out.println(reverseBinary);
Given a string as input, convert it into the number it represents. You can assume that the string consists of only numeric digits. It will not consist of negative numbers. Do not use Integer.parseInt to solve this problem.
MyApproach
I converted string to char array and stored the original number but I am unable to convert it into a single number
I tried converting individual elements but the digits can be of any length.So,It was difficult to follow that approach.
Hint:I have a hint that the numbers can be added using place values
For e.g if the number is 2300.I stored each number in the form of arrays.Then it should be 2*1000+3*100+0*10+0=2300
But I am unable to convert it into code.
Can anyone guide me how to do that?
Note I cannot use any inbuilt functions.
public int toNumber(String str)
{
char ch1[]=str.toCharArray();
int c[]=new int[ch1.length];
int k=0;
for(int i=0;i<c.length;i++)
{
if(ch1[i]==48)
{
c[k++]=0;
}
else if(ch1[i]==49)
{
c[k++]=1;
}
else if(ch1[i]==50)
{
c[k++]=2;
}
else if(ch1[i]==51)
{
c[k++]=3;
}
else if(ch1[i]==52)
{
c[k++]=4;
}
else if(ch1[i]==53)
{
c[k++]=5;
}
else if(ch1[i]==54)
{
c[k++]=6;
}
else if(ch1[i]==55)
{
c[k++]=7;
}
else if(ch1[i]==56)
{
c[k++]=8;
}
else if(ch1[i]==57)
{
c[k++]=9;
}
}
}
You don't need to do powers or keep track of your multiplier. Just multiply your running total by 10 each time you add in a new digit. And use c - '0' to turn a character into a number:
int n = 0;
for (int i = 0; i < str.length(); i++) {
n = n * 10 + str.charAt(i) - '0';
}
So for example for 1234 it goes
0 * 10 + 1 = 1
1 * 10 + 2 = 12
12 * 10 + 3 = 123
123 * 10 + 4 = 1234
A digit character ('0'-'9') can be converted into an integer value (0-9) using:
ch - '0'
This is because the digit characters are all consecutive in ASCII/Unicode.
As for calculating the full number, for the input 2300, you don't want:
2 * 1000 + 3 * 100 + 0 * 10 + 0
Instead, you'll want a more incremental approach using a loop:
r = 0
r = r * 10 + 2 (2)
r = r * 10 + 3 (23)
r = r * 10 + 0 (230)
r = r * 10 + 0 (2300)
This is much better than trying to calculate 1000 (Math.pow(10,3)), which your formula would require.
This should be enough information for you to code it. If not, create a new question.
If you loop through the char array you have and take the last value, put it through an if statement and add to an to number integer whatever that number is (use 10 if statements). Next go to the second to last value, and do the same thing only this time multiply the resulting numbers by 10 before adding it to the total number. Repeat this using 1 * 10^(value away from end) being multiplied to the number gotten from the if statements.
Well what comes to my mind when seeing this problem is to multiply the numbers you are getting with your current code with the place they have in the charArray:
int desiredNumber = 0;
for(int k=1; k<=c.length; k++) {
desiredNumber += c[k] * (Math.pow(10, c.length - k));
}
If you are not allowed to use the Math.pow() function then simply write one yourself with aid of a loop.
Greetings Raven
You can do
int no = 0;
for(int i = 0; i < c.length; i++){
no += c[i] * Math.pow(10, c.length - 1 - i);
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'd like to format a BigDecimal in Java to 8 Characters (including the seperator), rounding HALF-UP.
Some examples:
12345.6789 -> "12345.68"
123 -> " 123.0"
0.12345678 -> "0.123457"
1.5 -> " 1.5"
0.0045 -> " 0.0045"
12 -> " 12.0"
The result must have leading spaces to fill up to 8 characters.
What's the easiest way?
I'm pretty sure this is not the best way, but it's one way.
First note that if your numbers have more than six digits before the period, or more generally more than width - 2 digits before the period, your format with .0 will not work anymore.
String.format() uses half up as a rounding method, so you can use it as a first step to get your output to eight characters.
BigDecimal b = new BigDecimal(0.0045);
String format = "%8f";
String str = String.format(format, b);
Output:
12345.678900
123.000000
0.123457
1.500000
0.004500
12.000000
123456.000000
By default String.format() uses a precision of 6 for BigDecimal. To get your custom precision, you need to know how many digits are before the period and substract this number (+ 1 for the period itself) from the total width.
width - digits - 1
To get the number of digits you can simply check if (number % radix) == number applies for radix = 10, 100, 1000, ... As soon as it fits you know the number of digits.
public static int digitsBeforePeriod(BigDecimal b) {
int number = b.intValue();
int radix = 10;
int digits = 1;
while((number % radix) != number) {
radix *= 10;
++digits;
}
return digits;
}
So the next step is to modify the format:
BigDecimal b = new BigDecimal(0.0045);
int digits = digitsBeforePeriod(b);
String format = "%8." + (8 - digits - 1) + "f";
String str = String.format(format, b);
Output:
12345.68
123.0000
0.123457
1.500000
0.004500
12.00000
123456.0
Still there are lots of 0s, but at least the rounding is correct now. Now you specify that if a number is round to an integer, you want to print it with a .0 suffix, otherwise without.
To achieve this there might also exist clever formats, I didn't think any further though. The naive way to do this is simply:
while(str.endsWith("0") && !str.endsWith(".0")) {
str = str.substring(0, str.length()-1);
}
This removes the last character of the string until it either doesn't end on 0 at all or ends with .0.
Now the numbers will have the correct format, but are not aligned correctly:
12345.68
123.0
0.123457
1.5
0.0045
12.0
123456.0
To align them, just use the String.format() again.
str = String.format("%" + width + "s", str);
Output:
12345.68
123.0
0.123457
1.5
0.0045
12.0
123456.0
In the context this looks like the following. Note that I included a check wether or not the number can be formatted that way - if not, it will print Invalid. You can of course also just print the number, I just wanted to show the limitations of that format.
public static String trimToWidth(BigDecimal b, int width) {
String str = "Invalid";
int digits = digitsBeforePeriod(b);
// -2 for period and 0
if(digits <= width - 2) {
// use width and (width - digits - 1) as precision (-1 for period)
String format = "%" + width + "." + (width - digits - 1) + "f";
// rounds half-up
str = String.format(format, b);
// trim trailing 0s, unless it's .0
while(str.endsWith("0") && !str.endsWith(".0")) {
str = str.substring(0, str.length()-1);
}
}
// add spaces in front
str = String.format("%" + width + "s", str);
return str;
}
public static int digitsBeforePeriod(BigDecimal b) {
int number = b.intValue();
int radix = 10;
int d = 1;
while((number % radix) != number) {
radix *= 10;
++d;
}
return d;
}
public static void main(String[] args) {
double[] values = new double[] {
12345.6789, 123, 0.12345678,
1.5, 0.0045, 12, 123456, 1234567
};
BigDecimal[] bigs = new BigDecimal[values.length];
for(int i = 0; i < bigs.length; ++i) {
bigs[i] = new BigDecimal(values[i]);
System.out.println(trimToWidth(bigs[i], 8));
}
}
I require some input on the below logic.
It is kind of billing system takes the input and has a value associated with it.
A = 2 , 3A = 5
B = 3
C = 1 , 4C = 3
My code , should be such that take ABCCBAACCA , output should be value which is 16.
My solution as of now, I m thinking to count every element in the string, and them mod(modulus) by 3 for A , 4 for C (as in the above case, no need in case of B) every element in order to get the result.
I'm confused what data structure I should be using in order to implement such system.
In pseudocode I believe it would be:
Count all A's, B's and C's
Divide A's by 3 and multiply by 5
Modulo A's by 3 and multiply by 2
Multiply B's by 3
Divide C's by 4 and multiply by 3
Modulo C's by 4
Sum the 5 results.
In Ruby it could like something like this:
input = "ABCCBAACCA"
letters = ["A", "B", "C"]
total = 0
def score(letter,count)
if letter == "A"
((count/3)*5)+((count%3)*2)
elsif letter == "B"
count*3
else letter == "C"
((count/4)*3)+(count%4)
end
end
letters.each do |letter|
puts "#{letter}: #{score(letter, input.count(letter))}"
total += score(letter, input.count(letter))
end
puts "Total: #{total}"
Which produces:
A: 7
B: 6
C: 3
Total: 16
Well, the modulus operator won't help you since you will be getting 0 everytime is a multiple of 3 or 5, depending the letter you are evaluating (if thats what you trying to describe, sorry if i got it wrong).
I believe the easiest way is scanning the string and just adding the values.
When you encounter a third A you just add 1, instead of 2 (because you have to subtract 4, then add 5)
Similarly with C, you just add 0, instead of 1, when you encounter the fourth C.
You need 2 additional variables to keep the instances of A and C, and yes, you can use modulus operator to know if you just arrived to a multiple where you have to add either 1 or 0, depending the case.
Hope this helps a bit.
EDIT:
Here, I did a quick implementation. Feel free to optimize it if you really need it ;)
String value = "ABCCBAACCA";
int numA =0;
int numC =0;
int endResult = 0;
for (int x = 0; x < value.length(); x++)
{
if (value.charAt(x) =='A')
{
numA = numA +1;
endResult = endResult + ((numA%3 == 0)?1:2);
}
else if (value.charAt(x) =='B')
{
endResult = endResult +3;
}
else if (value.charAt(x) =='C')
{
numC = numC +1;
endResult = endResult + ((numC%4 == 0)?0:1);
}
}
System.out.println(endResult); //16 as expected
class CharBucket
attr_accessor :count
def initialize(thresholds)
#thresholds = thresholds
#count = 0
end
def total
#thresholds.inject([0, #count]) do |sum_left, a|
sum = sum_left[0]
left = sum_left[1]
sum += (left / a[0]) * a[1]
left %= a[0]
[sum, left]
end[0]
end
end
a = CharBucket.new({3 => 5, 1 => 2})
b = CharBucket.new({1 => 3})
c = CharBucket.new({4 => 3, 1 => 1})
buckets = {'A' => a, 'B' => b, 'C' => c}
"ABCCBAACCA".each_char{|c| buckets[c].count += 1 }
total = buckets.values.inject(0){|sum, b| sum += b.total} # => 16
Well, I would start with something like this:
public static void main(String[] args) {
// FIXME
String inputString = null;
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (Character c : inputString.toCharArray()) {
map = countCharacters(map, c);
}
}
private static Map<Character, Integer> countCharacters(Map<Character, Integer> map,
Character charatcer) {
map.put(charatcer,
(map.get(charatcer) != null) ? map.get(charatcer) + 1 :
Integer.valueOf(1));
return map;
}
and then introduce #vlasits steps from second to 5th, as this code above is first step in his pseudocode. It counts all characters in your string by making map of "character" : "its Occurences", if there was no such a character before, it puts 1 to the map.
On paper, binary arithmetic is simple, but as a beginning programmer, I'm finding it a little difficult to come up with algorithms for the addition, subtraction, multiplication and division of binary numbers.
I have two binary numbers stored as strings, assume that any leading zeroes have been dropped. How would I go about performing these operations on the two numbers?
Edit: I need to avoid converting them to an int or long.
Binary string to int:
int i = Integer.parseInt("10101011", 2);
int j = Integer.parseInt("00010", 2);
Then you can do anything you please with the two ints, eg:
i = i + j;
i = i - j;
And to get them back to a binary string:
String s = Integer.toBinaryString(i);
The algorithms, from wikipedia:
Addition:
The simplest arithmetic operation in
binary is addition. Adding two
single-digit binary numbers is
relatively simple, using a form of
carrying:
0 + 0 → 0
0 + 1 → 1
1 + 0 → 1
1 + 1 → 0, carry 1 (since 1 + 1 = 0 + 1 × 10 in binary)
Adding two "1" digits produces a digit
"0", while 1 will have to be added to
the next column.
Subtraction:
Subtraction works in much the same
way:
0 − 0 → 0
0 − 1 → 1, borrow 1
1 − 0 → 1
1 − 1 → 0
Subtracting a "1" digit from a "0"
digit produces the digit "1", while 1
will have to be subtracted from the
next column. This is known as
borrowing. The principle is the same
as for carrying. When the result of a
subtraction is less than 0, the least
possible value of a digit, the
procedure is to "borrow" the deficit
divided by the radix (that is, 10/10)
from the left, subtracting it from the
next positional value.
Multiplication:
Multiplication in binary is similar to
its decimal counterpart. Two numbers A
and B can be multiplied by partial
products: for each digit in B, the
product of that digit in A is
calculated and written on a new line,
shifted leftward so that its rightmost
digit lines up with the digit in B
that was used. The sum of all these
partial products gives the final
result.
Since there are only two digits in
binary, there are only two possible
outcomes of each partial
multiplication:
* If the digit in B is 0, the partial product is also 0
* If the digit in B is 1, the partial product is equal to A
For example, the binary numbers 1011
and 1010 are multiplied as follows:
1 0 1 1 (A)
× 1 0 1 0 (B)
---------
0 0 0 0 ← Corresponds to a zero in B
+ 1 0 1 1 ← Corresponds to a one in B
+ 0 0 0 0
+ 1 0 1 1
---------------
= 1 1 0 1 1 1 0
The following code implements binary addition without actually doing any arithmetic, binary or otherwise. The actual "addition" is done by lookupTable, and everything else is straight-up string manipulation. I wrote it with the intention of making it as instructive as possible, emphasizing the process instead of efficiency. Hope it helps.
public class BinaryArithmetic {
static String[] lookupTable = {
"0+0+0=00",
"0+0+1=01",
"0+1+0=01",
"0+1+1=10",
"1+0+0=01",
"1+0+1=10",
"1+1+0=10",
"1+1+1=11",
};
static String lookup(char b1, char b2, char c) {
String formula = String.format("%c+%c+%c=", b1, b2, c);
for (String s : lookupTable) {
if (s.startsWith(formula)) {
return s.substring(s.indexOf("=") + 1);
}
}
throw new IllegalArgumentException();
}
static String zeroPad(String s, int length) {
while (s.length() < length) {
s = "0" + s;
}
return s;
}
static String add(String s1, String s2) {
int length = Math.max(s1.length(), s2.length());
s1 = zeroPad(s1, length);
s2 = zeroPad(s2, length);
String result = "";
char carry = '0';
for (int i = length - 1; i >= 0; i--) {
String columnResult = lookup(s1.charAt(i), s2.charAt(i), carry);
result = columnResult.charAt(1) + result;
carry = columnResult.charAt(0);
}
if (carry == '1') {
result = carry + result;
}
return result;
}
public static void main(String args[]) {
System.out.println(add("11101", "1001"));
}
}
While we're at it, I might as well do multiply too.
static String multiply(String s1, String s2) {
String result = "";
String zeroSuffix = "";
for (int i = s2.length() - 1; i >= 0; i--) {
if (s2.charAt(i) == '1') {
result = add(result, s1 + zeroSuffix);
}
zeroSuffix += "0";
}
return result;
}
Working with binary arithmetic is really no different than the more familiar base 10. Let's take addition for example
(1) (1)
182 182 182 182 182
845 845 845 845 845
--- + --- + --- + --- + --- +
7 27 027 1027
So what did you do? You right-align the numbers to add, and you proceed right-to-left, adding one digit at a time, carrying over +1 to the left as necessary.
In binary, the process is exactly the same. In fact, it's even simpler because you only have 2 "digits" now, 0 and 1!
(1) (1) (1)
11101 11101 11101 11101 11101 11101 11101
1001 1001 1001 1001 1001 1001 1001
----- + ----- + ----- + ----- + ----- + ----- + ----- +
0 10 110 0110 00110 100110
The rest of the operations work similarly too: the same process that you use for base 10, works for base 2. And again, it's actually simpler because there are only 2 "digits", 0 and 1. This simplicity is why hardware likes the binary system.
Convert the binary strings to Integers and then operate on the Integers, e.g.
String add(String s1, String s2) {
int i1 = Integer.parseInt(s1);
int i2 = Integer.parseInt(s2);
return Integer.toBinaryString(i1 + i2);
}
The built-in BitSet class is very straight-forward to use for bit-level operations.