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

这题比较简单,算法过程就是遍历数组,记录到第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%,提示数组越界非法访问,但是最后实在没找出来。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值