您的位置:首页 > 编程语言

滴滴出行2017秋招笔试编程题(一)——连续最大和、末尾0的个数、进制转换

2017-01-07 16:08 260 查看


这题比较简单,算法过程就是遍历数组,记录到第i个数的连续最大和,在计算第i个数的连续最大和时,先判断到第i-1个数的连续最大和是正还是负,如果是负数,则到第i个数的连续最大和就是第i个数本身;如果是正数,则到第i个数的连续最大和就是到第(i-1)个数的连续最大和加上第i个数。代码如下:

public class MaxSubArray {
public static int FindGreatestSumOfSubArray(int[] array,int n) {
if(array == null || n == 0)
return 0;
int sum = Integer.MIN_VALUE;
int curSum = 0;
for(int i = 0; i < n; i++){
if(curSum <= 0)
curSum = array[i];
else
curSum += array[i];
if(curSum > sum)
sum = curSum;
}

return sum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
int n;
int array[] = new int[100005];
while(cin.hasNext()){
n = cin.nextInt();
for(int i = 0 ;i < n; i++){
array[i] = cin.nextInt();
}
System.out.println(FindGreatestSumOfSubArray(array,n));
}
}

}


以上代码在牛客网90%的测试用例通过,我用c++按这个思路写100%通过,后来发现牛客网的最后一个测试案例有问题。



这个题目一看就是大数问题,果然也被大数坑了好几次,思路是一边进行阶乘,一边计算末尾零的个数,同时把计算过的0去掉。但是光去掉零并不能使数字小多少,计算时间也没有少很多。其实两个数字相乘末尾零的个数只与这两个数字末尾的几位数字有关,这样我们就可以大胆地将乘数对100000大胆取余,一下把数字降了好几个数量级。代码如下:

public class countZero {
public static void main(String args[]){
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int result = 1;
int count = 0;
for(int i = 1;i <= n;i++){
result *= i;
if(result % 10 == 0){
count++;
result = result / 10;
}
if(result > 100000)
result = result % 100000;
}
while(result % 10 == 0){
count++;
result = result/10;
}
System.out.println(count);
}
}



这个题代码按照题目说的转化就好了

public class convertDec {
public static void main(String args[]){
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int m = cin.nextInt();
String str = convert(n,m);
for(int i = str.length() - 1; i >= 0; i--){
System.out.print(str.charAt(i));
}
}
static char ch[] = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z'};
public static String convert(int n,int m){
String str = "";
while(n != 0){
int num = n % m;
str += String.valueOf(ch[num]);
n = n / m;
}
return str;
}
}


在牛客网测试用例通过70%,提示数组越界非法访问,但是最后实在没找出来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: