Skip to content

Instantly share code, notes, and snippets.

@youssef3wi
Created March 30, 2024 16:43
Show Gist options
  • Select an option

  • Save youssef3wi/d668451c9d8dabb1d9b4bb3489b3f73c to your computer and use it in GitHub Desktop.

Select an option

Save youssef3wi/d668451c9d8dabb1d9b4bb3489b3f73c to your computer and use it in GitHub Desktop.
We like to measure the outcome of our activities and the similarities between different projects.
import java.util.Scanner;
import static java.lang.Integer.toBinaryString;
/**
* We like to measure the outcome of our activities and the similarities between
* different projects.
* <p>
* The measure of the similarity between two projects is the number of positions (in their
* binary representation) at which the corresponding bits of their identifiers are different.
* <p>
* Given two different projects {@literal n} and {@literal m}, write a function that returns their similarity.
* <p>
* <b>INPUT</b>
* <p><b>Line 1: </b> Two integers N and M</p>
* <p>
* <b>OUTPUT</b>
* <p>The similarity measure between N and M.</p>
* <p>
* <b>CONSTRAINTS</b>
* <p>0 < N,M < 100000000</p>
* <p>
* <b>EXAMPLE: </b>
* <table >
* <tr>
* <td>Input</td>
* <td>Output</td>
* </tr>
* <tr>
* <td>1 4</td>
* <td>2</td>
* </tr>
* </table>
*/
public class MeasureOutcome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // 1
int m = sc.nextInt(); // 4
String nBinary = new StringBuilder(toBinaryString(n)).reverse().toString();
String mBinary = new StringBuilder(toBinaryString(m)).reverse().toString();
// pad with zeros
int difference = Math.abs(nBinary.length() - mBinary.length()) + 1;
if (nBinary.length() < mBinary.length()) {
nBinary = String.format("%1$-" + difference + "s", nBinary).replace(' ', '0');
} else {
mBinary = String.format("%1$-" + difference + "s", mBinary).replace(' ', '0');
}
// Measure
int measure = 1;
for (int idx = 0; idx < nBinary.length(); idx++) {
if (mBinary.charAt(idx) == nBinary.charAt(idx)) {
measure = (int) Math.pow(2, idx);
}
}
System.out.println("Measure: " + measure);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment