-
编写一个函数,对传入的两个数组,判断第二个数组是否为第一个数组的子数组(要连续比对)。如果不是,返回 -1; 如果是,则返回在第一个数组中最大的下标。
public static int sub(int[]A, int[]B){ // add your code here }
Example: System.out.println(sub(new int[] {4,5,6,7,5,6,8}, new int[] {5,6})); // 4 System.out.println(sub(new int[] {4,5,7,5,8}, new int[] {5,6})); // -1 System.out.println(sub(new int[] {4,5,6,7,5,6,8}, new int[] {6})); // 5 System.out.println(sub(new int[] {4,5,6,7,5,6,8}, new int[] {4,5,6})); // 0
解题:
public class Solution { public static void main(String[] args) { System.out.println(sub(new int[]{4,5,6,7,5,6,8}, new int[]{5,6}));// 4 System.out.println(sub(new int[]{4,5,7,5,8}, new int[]{5,6}));// -1 System.out.println(sub(new int[]{4,5,6,7,5,6,8}, new int[]{6}));// 5 System.out.println(sub(new int[]{4,5,6,7,5,6,8}, new int[]{4,5,6}));// 0 } public static int sub(int[]A, int[] B){ String s1 = arr2String(A); String s2 = arr2String(B); return s1.lastIndexOf(s2); } private static String arr2String(int[]A){ StringBuilder sb = new StringBuilder(); for (int i: A ) { sb.append(i); } return sb.toString(); } }
-
编写一个函数实现对两个数字字符串进行十进制的加法操作,并返回求和结果,如果出错清返回“ERROR”。不能使用 BigInteger 等 java 库中的工具类。
public static String add(String numberA, String numberB){
// add your code here
}
Example:
System.out.println(add("123456789123456789123456789", "123456789123456789123456789")); 246913578246913578246913578
System.out.println(add("1", "
2")); // 3
System.out.println(add("A", "123456789123456789123456789")); // ERROR
解题:
public class Solution {
public static void main(String[] args) {
System.out.println(add("123456789123456789123456789", "123456789123456789123456789"));//246913578246913578246913578
System.out.println(add("1", "2"));//3
System.out.println(add("A", "1"));// ERROR
}
public static String add(String numberA, String numberB){
int index = 0;
int other = 0; // 进位
StringBuilder sb = new StringBuilder();
// 从个位开始相加
while(index < Math.max(numberA.length(), numberB.length() )) {
// 计算 A B 字符串的倒数位置
int a = numberA.length() - 1 - index;
int b = numberB.length() - 1 - index;
// 计算 A B 字符串倒数位置上的值,如果位置为 -1,则指默认补 0, 如果转换异常,则返回 Error
int numA = 0;
int numB = 0;
try {
numA = a >= 0 ? Integer.valueOf( String.valueOf(numberA.charAt(a))) : 0; // numberA 个位
numB = b >= 0 ? Integer.valueOf( String.valueOf(numberB.charAt(b))) : 0; // numberB 个位
}catch (NumberFormatException e){
return "ERROR";
}
int sum = numA+ numB + other;
other = sum / 10;
int num = sum % 10;
sb.append(num);
index ++;
}
return sb.reverse().toString();
}
}