2020華爲校招軟件測試:專業面試兩輪的算法題

專業面試筆試題1:計算二叉樹的深度 

public int computeTreeDepth(BinaryTree binaryTree){
        if(binaryTree == null){
            return 0;
        }
        if(binaryTree.lChild == null && binaryTree.rChild == null){
            return 1;
        }
        int lDepth = computeTreeDepth(binaryTree.lChild) + 1;
        int rDepth = computeTreeDepth(binaryTree.rChild) + 1;
        return Math.max(lDepth, rDepth);
    }


專業面試筆試題2:反轉數字,輸入一個32位整形數字a,輸出反轉後的數字,例如:123,輸出321;-2324,輸出-4232;1003400,輸出43001;如果輸入的數超過32位,則輸出0;
 

#include <iostream>
#include <math.h>
using namespace std;
int main() {
    int a,b=0,c[10],weiShu;
    cin >> a;
    
    if(a<-2147483647 || a>2147483647){
        b=1;
        cout<<b<<endl;
        return 0;
    } 
    //把各個位的數字取出來
    for(int i=0; i<10; i++){
        c[i] = a%10;
        a = a/pow(10,1);
    }
    //計算這個數字共幾位
    for(int j=9; j>=0; j--){
        if(c[j] != 0){
            weiShu = j;
            break;
        }
    }
    //反轉
    for(int z=weiShu; z>=0; z--){
        b = b+c[z]*pow(10,weiShu-z);
    }
    cout<<b<<endl;   
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章