We represent the Sudoku as a two-dimensional array. If you want to achieve two columns in one stack are swapped, we need to symmetrically swap the columns of the two-dimensional array. But in the teacher's code, why is the row of the array exchanged? And the result is correct.
private void permutateColumns(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
int[] array = field[a-1];
field[a-1] = field[b-1];
field[b-1] = array;
}
}
all code
package ubung;
import java.util.Random;
//-------------------------------------------------------------- a)
public class Sudoku {
final int n = 3;
final int gridsize = n*n;
int[][] field = new int[gridsize][gridsize];
Random random = new Random();
public Sudoku() {
int[] firstRow = {1,2,3,4,5,6,7,8,9};
//h): int[] firstRow = randomRow();
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < gridsize; j++)
field[i][j] = (i*n + i/n + j) % gridsize + 1;
//h): field[i][j] = firstRow[(i*n + i/n + j) % gridsize];
System.out.println(this);
}
//------------------------------------------------------------- g)
public Sudoku(int permutationCount) {
this();
randomPermutation(permutationCount);
}
//-------------------------------------------------------------- b)
/**Die Methode gibt ein Sudoku-Objekt als einen String zurueck
* #return der String eines Sudoku-Objektes
*/
public String toString() {
String str = line(25);
for(int i = 0; i < 9; i++){
str += "|";
for(int j = 0; j < 9; j++){
str += " " + get(i,j);
if(j == 2 || j == 5 || j == 8)
str += " |";
}
str += "\n";
if(i == 2 || i == 5 || i == 8){
str += line(25);
}
}
return str;
}
/**
* Getter for single entries
*/
private String get(int i, int j) {
if(i < 0 || i > gridsize + 1 || j < 0 || j > gridsize + 1) {
return " ";
}
int m = field[i][j];
if(m == 0)
return " ";
return ""+m;
}
private String line(int n){
String str = "";
for(int i = 0; i < n; i++)
str += "-";
return str+"\n";
}
//-------------------------------------------------------------- c)
/**
* Two rows in one band are swapped. This produces 3!^3 as much solutions. ?????????????????????????
*/
private void permutateRows(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
for(int i = 0; i < gridsize; i++) {
int temp = field[i][a-1];
field[i][a-1] = field[i][b-1];
field[i][b-1] = temp;
}
}
}
/**
* Two columns in one stack are swapped. This produces 3!^3 as much solutions. ????????????????????
*/
private void permutateColumns(int a, int b) {
if(a > 0 && a < 10 && b > 0 && b < 10) {
int[] array = field[a-1];
field[a-1] = field[b-1];
field[b-1] = array;
}
}
//-------------------------------------------------------------- d)
/**
* Two stacks are swapped. This produces 3! as much solutions.
*/
private void permutateStacks(int a, int b) {
if(b < a) {
permutateStacks(b,a);
return;
}
if(a == 1 && b == 2) {
permutateColumns(1,4);
permutateColumns(2,5);
permutateColumns(3,6);
}
else if(a == 1 && b == 3) {
permutateColumns(1,7);
permutateColumns(2,8);
permutateColumns(3,9);
}
else if(a == 2 && b == 3) {
permutateColumns(4,7);
permutateColumns(5,8);
permutateColumns(6,9);
}
}
/**
* Two bands are swapped. This produces 3! as much solutions.
*/
private void permutateBands(int a, int b) {
if(b < a) {
permutateBands(b,a);
return;
}
if(a == 1 && b == 2) {
permutateRows(1,4);
permutateRows(2,5);
permutateRows(3,6);
}
else if(a == 1 && b == 3) {
permutateRows(1,7);
permutateRows(2,8);
permutateRows(3,9);
}
else if(a == 2 && b == 3) {
permutateRows(4,7);
permutateRows(5,8);
permutateRows(6,9);
}
}
//-------------------------------------------------------------- e)
/**
* Two rows in one band are swapped. This produces 3!^3 as much solutions.
*/
private void permutateRows() {
int block = random.nextInt(3);
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateRows(a+block*3,b+block*3);
}
/**
* Two columns in one stack are swapped. This produces 3!^3 as much solutions.
*/
private void permutateColumns() {
int block = random.nextInt(3);
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateColumns(a+block*3,b+block*3);
}
private void permutateStacks() {
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateStacks(a,b);
}
private void permutateBands() {
int a = random.nextInt(3)+1;
int b = random.nextInt(3)+1;
permutateBands(a,b);
}
//-------------------------------------------------------------- f)
/**
* The matrix is transposed. This produces double as much solutions.
*/
private void transpose() {
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < i; j++) {
int temp = field[j][i];
field[j][i] = field[i][j];
field[i][j] = temp;
}
}
//-------------------------------------------------------------- g)
private void randomPermutation(){
switch(random.nextInt(5)) {
case 0: permutateRows(); break;
case 1: permutateColumns(); break;
case 2: permutateStacks(); break;
case 3: permutateBands(); break;
case 4: transpose();
default:
}
}
private void randomPermutation(int n){
for(int i = 0; i < n; i++)
randomPermutation();
}
//-------------------------------------------------------------- h)
/**
* Returns random row of digits. Used to relabel digits in the initial matrix
* This yields 9! as much solutions.
*/
private int[] randomRow(){
boolean[] used = new boolean[gridsize];
int[] row = new int[gridsize];
for(int i = 0; i < gridsize; i++) {
int candidate = random.nextInt(gridsize);
if(!used[candidate]){
used[candidate] = true;
row[i] = candidate+1;
}
else {
i--;
}
}
return row;
}
//-------------------------------------------------------------- i)
private void hide(int n) {
if(n < 0)
n = 0;
if(n > 81)
n = 81;
for(int k = 0; k < n; k++) {
int i = random.nextInt(9); //在方法调用返回介于0(含)和n(不含)伪随机,均匀分布的int值。
int j = random.nextInt(9);
if(field[i][j] != 0)
field[i][j] = 0;
else
k--;
}
}
/*****************************************/ //gegeben
public static void main(String[] args){
Sudoku s = new Sudoku(100000);
System.out.println(s);
s.hide(50);
System.out.println(s);
}
}
We represent the Sudoku as a two-dimensional array. If you want to achieve two columns in one stack are swapped, we need to symmetrically swap the columns of the two-dimensional array. But in the teacher's code, why is the row of the array exchanged? And the result is correct.
If we notate the indices of the 2D array as field[x][y], the provided solution code uses x as the column index and y as the row index. It is important to note that the provided method is not the only correct solution. It would be just as correct to implement x as the row index and y as the column index, so long as the methods were implemented correctly.
I'm trying to do the Algorithm programming assignment of Princeton , and I met a problem about the memory test. The assignment requires us run the percolation program N times and find the medium of the result, and I write a percolationtest.java and for each time, I create an instance variable, it worked, but use too much memory, and the instructor suggests me to use local variable, but I don't know how. Can some one help me and give me some advice, I really appreciate it.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private int []count;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
} // perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
return totalFraction/T;
} // sample mean of percolation threshold
public double stddev() {
double u = this.mean();
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
public class Percolation {
private boolean[][] site;
private WeightedQuickUnionUF uf;
private int N;
public Percolation(int N) {
if (N < 1)
throw new IllegalArgumentException();
else {
site = new boolean[N + 2][N + 2];
for (int j = 1; j <= N; j++) {
site[0][j] = true;
site[N + 1][j] = true;
}
uf = new WeightedQuickUnionUF((N + 2) * (N + 2));
for (int i = 1; i <= N; i++) {
uf.union(0, i);
}
this.N = N;
}
}
public void open(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else {
if (!site[i][j]) {
site[i][j] = true;
if (site[i - 1][j]) {
uf.union((N + 2) * (i - 1) + j, (N + 2) * i + j);
}
if (site[i + 1][j]) {
uf.union((N + 2) * i + j, (N + 2) * (i + 1) + j);
}
if (site[i][j + 1]) {
uf.union((N + 2) * i + (j + 1), (N + 2) * i + j);
}
if (site[i][j - 1]) {
uf.union((N + 2) * i + (j - 1), (N + 2) * i + j);
}
}
}
}
public boolean isOpen(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j];
}
public boolean isFull(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j] && (i == 1 || uf.connected((N + 2) * i + j, 0));
}
public boolean percolates() {
for (int i = 1; i <= N; i++) {
if (this.isFull(N, i)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
}
}
Added meanValue instance variable to keep mean value and replaced it in multiple places where you used to call mean() method which was over head to calculate again and again. Also modified "int[] count" as local variable which you were not using outside the constructor. post your "Percolation" and "StdRandom" classes for more optimization of code. you can run this code and test, it should reduce the runtime than yours.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private double meanValue;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
int [] count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
}
// perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
meanValue = totalFraction/T;
return meanValue;
} // sample mean of percolation threshold
public double stddev() {
double u = meanValue;
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
A positive number n is consecutive-factored if and only if it has factors, i and j where i > 1, j > 1 and j = i +1. I need a function that returns 1 if its argument is consecutive-factored, otherwise it returns 0.For example, 24=2*3*4 and 3 = 2+1 so it has the function has to return 1 in this case.
I have tried this:
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number %i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a =al(0);
int b = al(1);
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}
Can anyone help me with this problem?
First check if its even, then try trial division
if(n%2!=0) return 0;
for(i=2;i<sqrt(n);++i) {
int div=i*(i+1);
if( n % div ==0) { return 1; }
}
return 0;
very inefficient, but fine for small numbers. Beyond that try a factorisation algorithm from http://en.wikipedia.org/wiki/Prime_factorization.
I have solved my problem with the above code. Following is the code.
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number % i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
Object ia[] = al.toArray();
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a = ((Integer) ia[0]).intValue();
int b = ((Integer) ia[1]).intValue();
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}
Does anyone know how to add 2 binary numbers, entered as binary, in Java?
For example, 1010 + 10 = 1100.
Use Integer.parseInt(String, int radix).
public static String addBinary(){
// The two input Strings, containing the binary representation of the two values:
String input0 = "1010";
String input1 = "10";
// Use as radix 2 because it's binary
int number0 = Integer.parseInt(input0, 2);
int number1 = Integer.parseInt(input1, 2);
int sum = number0 + number1;
return Integer.toBinaryString(sum); //returns the answer as a binary value;
}
To dive into fundamentals:
public static String binaryAddition(String s1, String s2) {
if (s1 == null || s2 == null) return "";
int first = s1.length() - 1;
int second = s2.length() - 1;
StringBuilder sb = new StringBuilder();
int carry = 0;
while (first >= 0 || second >= 0) {
int sum = carry;
if (first >= 0) {
sum += s1.charAt(first) - '0';
first--;
}
if (second >= 0) {
sum += s2.charAt(second) - '0';
second--;
}
carry = sum >> 1;
sum = sum & 1;
sb.append(sum == 0 ? '0' : '1');
}
if (carry > 0)
sb.append('1');
sb.reverse();
return String.valueOf(sb);
}
Martijn is absolutely correct, to piggyback and complete the answer
Integer.toBinaryString(sum);
would give your output in binary as per the OP question.
You can just put 0b in front of the binary number to specify that it is binary.
For this example, you can simply do:
Integer.toString(0b1010 + 0b10, 2);
This will add the two in binary, and Integer.toString() with 2 as the second parameter converts it back to binary.
The original solution by Martijn will not work for large binary numbers. The below code can be used to overcome that.
public String addBinary(String s1, String s2) {
StringBuilder sb = new StringBuilder();
int i = s1.length() - 1, j = s2.length() -1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) sum += s2.charAt(j--) - '0';
if (i >= 0) sum += s1.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
public class BinaryArithmetic {
/*-------------------------- add ------------------------------------------------------------*/
static String add(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 + number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
/*-------------------------------multiply-------------------------------------------------------*/
static String multiply(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 * number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
/*----------------------------------------substraction----------------------------------------------*/
static String sub(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 - number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
/*--------------------------------------division------------------------------------------------*/
static String div(double a, double b) {
System.out.println(a + "first val :" + b);
int a1 = (int) a;
int b1 = (int) b;
String s1 = Integer.toString(a1);
String s2 = Integer.toString(b1);
int number0 = Integer.parseInt(s1, 2);
int number1 = Integer.parseInt(s2, 2);
int sum = number0 / number1;
String s3 = Integer.toBinaryString(sum);
return s3;
}
}
Another interesting but long approach is to convert each of the two numbers to decimal, adding the decimal numbers and converting the answer obtained back to binary!
Java solution
static String addBinary(String a, String b) {
int lenA = a.length();
int lenB = b.length();
int i = 0;
StringBuilder sb = new StringBuilder();
int rem = Math.abs(lenA-lenB);
while(rem >0){
sb.append('0');
rem--;
}
if(lenA > lenB){
sb.append(b);
b = sb.toString();
}else{
sb.append(a);
a = sb.toString();
}
sb = new StringBuilder();
char carry = '0';
i = a.length();
while(i > 0){
if(a.charAt(i-1) == b.charAt(i-1)){
sb.append(carry);
if(a.charAt(i-1) == '1'){
carry = '1';
}else{
carry = '0';
}
}else{
if(carry == '1'){
sb.append('0');
carry = '1';
}else{
carry = '0';
sb.append('1');
}
}
i--;
}
if(carry == '1'){
sb.append(carry);
}
sb.reverse();
return sb.toString();
}
public String addBinary(String a, String b) {
int carry = 0;
StringBuilder sb = new StringBuilder();
for(int i = a.length() - 1, j = b.length() - 1;i >= 0 || j >= 0;i--,j--){
int sum = carry + (i >= 0 ? a.charAt(i) - '0':0) + (j >= 0 ? b.charAt(j) - '0' : 0);
sb.append(sum%2);
carry =sum / 2;
}
if(carry > 0) sb.append(carry);
sb.reverse();
return sb.toString();
}
I've actually managed to find a solution to this question without using the stringbuilder() function. Check this out:
public void BinaryAddition(String s1,String s2)
{
int l1=s1.length();int c1=l1;
int l2=s2.length();int c2=l2;
int max=(int)Math.max(l1,l2);
int arr1[]=new int[max];
int arr2[]=new int[max];
int sum[]=new int[max+1];
for(int i=(arr1.length-1);i>=(max-l1);i--)
{
arr1[i]=(int)(s1.charAt(c1-1)-48);
c1--;
}
for(int i=(arr2.length-1);i>=(max-l2);i--)
{
arr2[i]=(int)(s2.charAt(c2-1)-48);
c2--;
}
for(int i=(sum.length-1);i>=1;i--)
{
sum[i]+=arr1[i-1]+arr2[i-1];
if(sum[i]==2)
{
sum[i]=0;
sum[i-1]=1;
}
else if(sum[i]==3)
{
sum[i]=1;
sum[i-1]=1;
}
}
int c=0;
for(int i=0;i<sum.length;i++)
{
System.out.print(sum[i]);
}
}
The idea is same as discussed in few of the answers, but this one is a much shorter and easier to understand solution (steps are commented).
// Handles numbers which are way bigger.
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1;
int j = b.length() -1;
int carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) { sum += b.charAt(j--) - '0' };
if (i >= 0) { sum += a.charAt(i--) - '0' };
// Added number can be only 0 or 1
sb.append(sum % 2);
// Get the carry.
carry = sum / 2;
}
if (carry != 0) { sb.append(carry); }
// First reverse and then return.
return sb.reverse().toString();
}
i tried to make it simple this was sth i had to deal with with my cryptography prj its not efficient but i hope it
public String binarysum(String a, String b){
int carry=0;
int maxim;
int minim;
maxim=Math.max(a.length(),b.length());
minim=Math.min(a.length(),b.length());
char smin[]=new char[minim];
char smax[]=new char[maxim];
if(a.length()==minim){
for(int i=0;i<smin.length;i++){
smin[i]=a.charAt(i);
}
for(int i=0;i<smax.length;i++){
smax[i]=b.charAt(i);
}
}
else{
for(int i=0;i<smin.length;i++){
smin[i]=b.charAt(i);
}
for(int i=0;i<smax.length;i++){
smax[i]=a.charAt(i);
}
}
char[]sum=new char[maxim];
char[] st=new char[maxim];
for(int i=0;i<st.length;i++){
st[i]='0';
}
int k=st.length-1;
for(int i=smin.length-1;i>-1;i--){
st[k]=smin[i];
k--;
}
// *************************** sum begins here
for(int i=maxim-1;i>-1;i--){
char x= smax[i];
char y= st[i];
if(x==y && x=='0'){
if(carry==0)
sum[i]='0';
else if(carry==1){
sum[i]='1';
carry=0;
}
}
else if(x==y && x=='1'){
if(carry==0){
sum[i]='0';
carry=1;
}
else if(carry==1){
sum[i]='1';
carry=1;
}
}
else if(x!=y){
if(carry==0){
sum[i]='1';
}
else if(carry==1){
sum[i]='0';
carry=1;
}
} }
String s=new String(sum);
return s;
}
class Sum{
public int number;
public int carry;
Sum(int number, int carry){
this.number = number;
this.carry = carry;
}
}
public String addBinary(String a, String b) {
int lengthOfA = a.length();
int lengthOfB = b.length();
if(lengthOfA > lengthOfB){
for(int i=0; i<(lengthOfA - lengthOfB); i++){
b="0"+b;
}
}
else{
for(int i=0; i<(lengthOfB - lengthOfA); i++){
a="0"+a;
}
}
String result = "";
Sum s = new Sum(0,0);
for(int i=a.length()-1; i>=0; i--){
s = addNumber(Character.getNumericValue(a.charAt(i)), Character.getNumericValue(b.charAt(i)), s.carry);
result = result + Integer.toString(s.number);
}
if(s.carry == 1) { result += s.carry ;}
return new StringBuilder(result).reverse().toString();
}
Sum addNumber(int number1, int number2, int carry){
Sum sum = new Sum(0,0);
sum.number = number1 ^ number2 ^ carry;
sum.carry = (number1 & number2) | (number2 & carry) | (number1 & carry);
return sum;
}
import java.util.*;
public class BitAddition {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
int[] arr1 = new int[len];
int[] arr2 = new int[len];
int[] sum = new int[len+1];
Arrays.fill(sum, 0);
for(int i=0;i<len;i++){
arr1[i] =sc.nextInt();
}
for(int i=0;i<len;i++){
arr2[i] =sc.nextInt();
}
for(int i=len-1;i>=0;i--){
if(sum[i+1] == 0){
if(arr1[i]!=arr2[i]){
sum[i+1] = 1;
}
else if(arr1[i] ==1 && arr2[i] == 1){
sum[i+1] =0 ;
sum[i] = 1;
}
}
else{
if((arr1[i]!=arr2[i])){
sum[i+1] = 0;
sum[i] = 1;
}
else if(arr1[i] == 1){
sum[i+1] = 1;
sum[i] = 1;
}
}
}
for(int i=0;i<=len;i++){
System.out.print(sum[i]);
}
}
}
One of the simple ways is as:
convert the two strings to char[] array and set carry=0.
set the smallest array length in for loop
start for loop from the last index and decrement it
check 4 conditions(0+0=0, 0+1=1, 1+0=1, 1+1=10(carry=1)) for binary addition for each element in both the arrays and reset the carry accordingly.
append the addition in stringbuffer
append rest of the elements from max size array to stringbuffer but check consider carry while appending
print stringbuffer in reverse order for the answer.
//The java code is as
static String binaryAdd(String a, String b){
int len = 0;
int size = 0;
char[] c1 = a.toCharArray();
char[] c2 = b.toCharArray();
char[] max;
if(c1.length > c2.length){
len = c2.length;
size = c1.length;
max = c1;
}
else
{
len = c1.length;
size = c2.length;
max = c2;
}
StringBuilder sb = new StringBuilder();
int carry = 0;
int p = c1.length - 1;
int q = c2.length - 1;
for(int i=len-1; i>=0; i--){
if(c1[p] == '0' && c2[q] == '0'){
if(carry == 0){
sb.append(0);
carry = 0;
}
else{
sb.append(1);
carry = 0;
}
}
if((c1[p] == '0' && c2[q] == '1') || (c1[p] == '1' && c2[q] == '0')){
if(carry == 0){
sb.append(1);
carry = 0;
}
else{
sb.append(0);
carry = 1;
}
}
if((c1[p] == '1' && c2[q] == '1')){
if(carry == 0){
sb.append(0);
carry = 1;
}
else{
sb.append(1);
carry = 1;
}
}
p--;
q--;
}
for(int j = size-len-1; j>=0; j--){
if(max[j] == '0'){
if(carry == 0){
sb.append(0);
carry = 0;
}
else{
sb.append(1);
carry = 0;
}
}
if(max[j] == '1'){
if(carry == 0){
sb.append(1);
carry = 0;
}
else{
sb.append(0);
carry = 1;
}
}
}
if(carry == 1)
sb.append(1);
return sb.reverse().toString();
}
import java.io.;
import java.util.;
public class adtbin {
static Scanner sc=new Scanner(System.in);
public void fun(int n1) {
int i=0;
int sum[]=new int[20];
while(n1>0) {
sum[i]=n1%2; n1=n1/2; i++;
}
for(int a=i-1;a>=0;a--) {
System.out.print(sum[a]);
}
}
public static void main() {
int m,n,add;
adtbin ob=new adtbin();
System.out.println("enter the value of m and n");
m=sc.nextInt();
n=sc.nextInt();
add=m+n;
ob.fun(add);
}
}
you can write your own One.
long a =100011111111L;
long b =1000001111L;
int carry = 0 ;
long result = 0;
long multiplicity = 1;
while(a!=0 || b!=0 || carry ==1){
if(a%10==1){
if(b%10==1){
result+= (carry*multiplicity);
carry = 1;
}else if(carry == 1){
carry = 1;
}else{
result += multiplicity;
}
}else if (b%10 == 1){
if(carry == 1){
carry = 1;
}else {
result += multiplicity;
}
}else {
result += (carry*multiplicity);
carry = 0;
}
a/=10;
b/=10;
multiplicity *= 10;
}
System.out.print(result);
it works just by numbers , no need string , no need SubString and ...
package Assignment19thDec;
import java.util.Scanner;
public class addTwoBinaryNumbers {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.println("Enter 1st Binary Number");
int number1=sc.nextInt();
int reminder1=0;
int number2=sc.nextInt();
int reminder2=0;
int carry=0;
double sumResult=0 ;int add = 0
;
int n;
int power=0;
while (number1>0 || number2>0) {
/*System.out.println(number1 + " " +number2);*/
reminder1=number1%10;
number1=number1/10;
reminder2=number2%10;
number2=number2/10;
/*System.out.println(reminder1 +" "+ reminder2);*/
if(reminder1>1 || reminder2>1 ) {
System.out.println("not a binary number");
System.exit(0);
}
n=reminder1+reminder2+carry;
switch(n) {
case 0:
add=0; carry=0;
break;
case 1: add=1; carry=0;
break;
case 2: add=0; carry=1;
break;
case 3: add=1;carry=1;
break;
default: System.out.println("not a binary number ");
}
sumResult=add*(Math.pow(10, power))+sumResult;
power++;
}
sumResult=carry*(Math.pow(10, power))+sumResult;
System.out.println("\n"+(int)sumResult);
}
}
Try this, tested with binary and decimal and its self explanatory
public String add(String s1, String s2, int radix){
int s1Length = s1.length();
int s2Length = s2.length();
int reminder = 0;
int carry = 0;
StringBuilder result = new StringBuilder();
int i = s1Length -1;
int j = s2Length -1;
while (i >=0 && j>=0) {
int operand1 = Integer.valueOf(s1.charAt(i)+"");
int operand2 = Integer.valueOf(s2.charAt(j)+"");
reminder = (operand1+operand2+carry) % radix;
carry = (operand1+operand2+carry) / radix;
result.append(reminder);
i--;j--;
}
while(i>=0){
int operand1 = Integer.valueOf(s1.charAt(i)+"");
reminder = (operand1+carry) % radix;
carry = (operand1+carry) / radix;
result.append(reminder);
i--;
}
while(j>=0){
int operand1 = Integer.valueOf(s2.charAt(j)+"");
reminder = (operand1+carry) % radix;
carry = (operand1+carry) / radix;
result.append(reminder);
j--;
}
return result.reverse().toString();
}
}
static int addBinaryNumbers(String a, String b) {
int firstToDecimal = 0;
int secondToDecimal = 0;
for (int i = a.length() - 1, count = 0; i >= 0; i--, count++) {
firstToDecimal += (Math.pow(2, count) * Integer.parseInt(String.valueOf(a.toCharArray()[i])));
}
for (int i = b.length() - 1, count = 0; i >= 0; i--, count++) {
secondToDecimal += (Math.pow(2, count) * Integer.parseInt(String.valueOf(b.toCharArray()[i])));
}
return firstToDecimal + secondToDecimal;
}
public static void main(String[] args) {
System.out.println(addBinaryNumbers("101", "110"));
}
here's a python version that
def binAdd(s1, s2):
if not s1 or not s2:
return ''
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) + int(s2[i])
if s == 2: #1+1
if carry == 0:
carry = 1
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
elif s == 1: # 1+0
if carry == 1:
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
else: # 0+0
if carry == 1:
result = "%s%s" % (result, '1')
carry = 0
else:
result = "%s%s" % (result, '0')
i = i - 1;
if carry>0:
result = "%s%s" % (result, '1')
return result[::-1]
import java.util.Scanner;
{
public static void main(String[] args)
{
String b1,b2;
Scanner sc= new Scanner(System.in);
System.out.println("Enter 1st binary no. : ") ;
b1=sc.next();
System.out.println("Enter 2nd binary no. : ") ;
b2=sc.next();
int num1=Integer.parseInt(b1,2);
int num2=Integer.parseInt(b2,2);
int sum=num1+num2;
System.out.println("Additon is : "+Integer.toBinaryString(sum));
}
}