面试题(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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值