package m08d03;
/**
* @author JackarooZhang
* @date 2018/8/3 7:44
*/
/**
*
* 有两个字符串(可能包含空格),请找出其中最长的公共连续子串, 输出其长度。
*
* 输入
*
* 给定两行字符串
*
* 输出
*
* 输出这两个字符串的最长公共连续子串的长度
*
*
*
* 样例输入
*
* abcde
*
* bcd
*
* 样例输出
*
* 3
*/
public class Item01 {
public static void main(String[] args) {
String a = "abcde";
String b = "bcd";
System.out.println(solution(a, b));
}
public static int solution(String a, String b) {
int n = a.length(), m = b.length();
int[][] dp = new int[n][m];
int max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a.charAt(i) == b.charAt(j)) {
if (i > 0 && j > 0) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = 1;
}
if (dp[i][j] > max) max = dp[i][j];
}
}
}
return max;
}
}
package m08d03;
/**
* @author JackarooZhang
* @date 2018/8/3 7:52
*/
/**
* 两个int32整数m和n的二进制表达,计算有多少个位(bit)不同?
*
* 输入
*
* 一行中给定两个数字
*
* 输出
*
* 输出这两个数字中bit不同的个数
*
*
*
* 样例输入
*
* 15 8
*
* 样例输出
*
* 3
*/
public class Item02 {
public static void main(String[] args) {
System.out.println(solution(15, 8));
}
public static int solution(int n, int m) {
int max = 0;
int rs = n ^ m;
StringBuilder s = new StringBuilder();
while (rs > 0) {
if (rs%2 == 1) {
s.append('1');
}
rs /= 2;
}
return s.length();
}
}
package m08d03;
import java.util.Scanner;
/**
* @author JackarooZhang
* @date 2018/8/3 14:32
*/
/**
* 对于一个正整数,我们认为它的光棍指数是它二进制表示下1的个数。
* 通常认为光棍指数越高,这个数就越孤单。那么问题来了,对于给定的[a,b]区间中。最孤单的数字是谁呢?
* 如果光棍指数相同,最孤单的就是最小的那个数。
*
* 输入:
* 2
* 0 14
* 100 1000
*
* 输出:
* Case 1: 7
* Case 2: 511
*/
public class Item03 {
/**
看一下数字规模,穷举每个数求其二进制表示中1的个数,显然会超时。
可以这样想,既然要求"1"最多的数,那么我就对一个数从低位开始,将其低位上的0不断换成1,
比较换之后的结果是否在区间内就行了。
关键:result |= result + 1; */
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i = 1; i <= t; i++){
long x = sc.nextLong();
long y = sc.nextLong();
long res = x;
while((res | (res + 1)) <= y){
res |= (res + 1);
}
System.out.println("Case " + i + ": " + res);
}
}
public static void main2(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] rs = new int[n];
for (int i = 0; i < n; i++) {
int start = sc.nextInt();
int end = sc.nextInt();
rs[i] = lonelyNumber(start, end);
}
sc.close();
for (int i = 0; i < rs.length; i++) {
System.out.println("Case " + (i + 1) + ": " + rs[i]);
}
}
public static int lonelyNumber(int start, int end) {
int lonelyNum = start;
int max = Integer.MIN_VALUE;
for (int i = start; i <= end; i++) {
int c = countOfOne(i);
if (c > max) {
lonelyNum = i;
max = c;
}
}
return lonelyNum;
}
public static int countOfOne(int n) {
int count = 0;
while (n > 0) {
int mod = n % 2;
if (mod == 1) count++;
n = n / 2;
}
return count;
}
}