1.题目描述
二货小易有一个W*H的网格盒子,网格的行编号为0H-1,网格的列编号为0W-1。每个格子至多可以放一块蛋糕,任意两块蛋糕的欧几里得距离不能等于2。
对于两个格子坐标(x1,y1),(x2,y2)的欧几里得距离为:
( (x1-x2) * (x1-x2) + (y1-y2) * (y1-y2) ) 的算术平方根
小易想知道最多可以放多少块蛋糕在网格盒子里。
输入描述:
每组数组包含网格长宽W,H,用空格分割.(1 ≤ W、H ≤ 1000)
输出描述:
输出一个最多可以放的蛋糕数
示例1
输入
3 2
输出
4
( (x1-x2) * (x1-x2) + (y1-y2) * (y1-y2) ) 的算术平方根 不等于2
即 ((x1-x2 ) * (x1-x2) + (y1-y2) * (y1-y2) ) 不等于4
这样的情况有五种可能的结果:
1+3=4 ( 1 )
3+1=4 ( 2 )
2+2=4 ( 3 )
0+4=4 ( 4 )
4+0=4 ( 5 )
由上面得到( 1 ) ( 2 ) ( 3 ) 不符合
0+4=4 ( 4 ) x1 = x2 , y1 = 2 + y2
4+0=4 ( 5 ) x1 = 2 + x2 , y1 = y2
那么就是说如果[i][j]位置放了蛋糕,那么[i + 2][j]和[i][j + 2]位置不能放蛋糕`
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int w = scanner.nextInt();
int h = scanner.nextInt();
int[][] arr = new int[w][h]; //默认数组中元素均为0
int count = 0;
for(int i = 0; i < w; i++){
for(int j = 0; j < h; j++){
if(arr[i][j] == 0){ //等于0时可以放蛋糕
count++;
if(i + 2 < w){ //防止i+2越界
arr[i + 2][j] = 1; //等于1时不可以放蛋糕
}
if(j + 2 < h){ //防止j+2越界
arr[i][j + 2] = 1;
}
}
}
}
System.out.println(count);
}
}
}
2.题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
返回值描述:
如果是合法的数值表达则返回该数字,否则返回0
示例1
输入
"+2147483647"
返回值
2147483647
示例2
输入
"1a33"
返回值
0
public class Solution {
public int StrToInt(String str) {
char[] ch = str.toCharArray();
if(ch == null || ch.length == 0){
return 0;
}
int flag = 1;
if(ch[0] =='+'){
flag = 1;
ch[0] = '0';
}else if(ch[0] == '-'){
flag = -1;
ch[0] = '0';
}
int sum = 0;
for(int i = 0; i < ch.length; i++){
if(ch[i] < '0' || ch[i] > '9'){
sum = 0;
break;
}
sum = sum * 10 + ch[i] - '0';
}
return flag * sum;
}
}