滴滴出行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%,提示數組越界非法訪問,但是最後實在沒找出來。

發佈了108 篇原創文章 · 獲贊 20 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章