面試題(4)

斐波那契數列

  • 從第三項開始,每一項都等於前兩項之和進行計算

1、遞歸
#include

    using namespace std;
    fibonacci(int n)
    {
            if(n==1)
            {
                    return 1;
            }
            if(n==2)
            {
                    return 1;
            }
            if(n>2)
            {
                return fibonacci(n-1)+fibonacci(n-2);
            }
            if(n<1)
            {
                    return 0;
            }
    }

2、非遞歸

fibonacci(int n)
{
    long temp[2];
    temp[0] = 1;
    temp[1] = 1;
    if(n == 1)
    {
        return temp[0];     
    }
    if(n == 2)
    {
        return temp[1];     
    }
    for(int index = 3;index <= n;index++)
    {
        long temp1 = temp[0];
        long temp2 = temp[1];
        temp[0] = temp2;
        temp[1] = temp1 + temp2;        
    }   
        return temp[1]; 
}

十進制數轉換成二進制

#include <iostream>
#include <vector>
#include <stack>

void convert(long n,vector<long>& bit)
{
    stack<long> tempstack;
    long temp = n;
    while(temp != 1)    
    {
        long temp1 = temp % 2;
        tempstack.push(temp1);
        temp = temp / 2;        
    }   
    tempstack.push(1);
    while(tempstack.empty() == false)
    {
        long temp2 = tempstack.top();
        bit.push_back(temp2);
        tempstack.pop();        
    }   
}

int main()
{
    vector<long> bit;
    convert(11,bit);
    vector<long>::iterator it = bit.begin();
    while(it != bit.end())
    {
        cout << *it;
        it++;       
    } 
    return 0;   
}

素數:大於1

void GetPrimer(long n,vector<long>& primer)
{
    for(long index = 2;index <= n;index++)
    {
        bool isP = true;        
        for(long j=2;j <index;j++)
        {
            if(index % j == 0)
            {
                isp = false;
                break;  
            }               
        }
        if(isP)
        {
            primer.push_back(index);            
        }       
    }   
}

int main()
{
    vector<long> primer;
    GetPrimer(100,primer);
    vector<long>::iterator it = primer.begin();
    while(it != primer.end())
    {
        cout << *it << endl;
        it++;       
    }   
}

字符串轉換爲整數

void StringToLong(string str,long& lvalue)
{
    string::size_type index = 0;
    for(index=0;index<str.size();index++)
    {
        char a = '0';
        char b = '9';
        if((str[index]) > a && (str[index] < b))
        {
            long value = str[index]-48;
            lvalue = value + lvalue*10;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章