牛客华为机试题刷题笔记(二)

本文记录了牛客上华为笔试的编程题解,包括数字颠倒、字符串操作、句子逆序、最长路径查找、位操作、购物单优化、坐标移动、IP地址分类等。涉及逆序操作、优先级队列、0-1背包问题、IP和掩码有效性判断等技巧。
摘要由CSDN通过智能技术生成

所有代码都在github

11.数字颠倒

颠倒就是逆序,可以把数字to_string一下然后再reserve
我的做法是按数字的方式处理,模10除10

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
    string str;
    while(n)
    {
        str+=to_string(n%10);
        n/=10;
    }
    cout<<str<<endl;
    }
    return 0;

}

12.字符串翻转

利用STL逆向迭代器和构造函数搞定

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string n;
    while(getline(cin,n))
    {
    string str(n.rbegin(),n.rend());
    cout<<str<<endl;
    }
    return 0;

}

13.句子逆序

"hello world"变成"world hello"
这个要逆转两次,先对整个句子进行逆序
"dlrow olleh"
再逐个单词逆序
"world hello"

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
    string line;
    while(getline(cin,line))
    {
    string tmp(line.rbegin(),line.rend());
    stringstream ss(tmp);
    string word;
    vector<string>words;
    while(ss>>word)
    {
        words.push_back(string(word.rbegin(),word.rend()));
        words.push_back(" ");
    }
    for(int i=0;i<words.size();++i)
    {
        if(i==words.size()-1)
        words[i].pop_back();    
        cout<<words[i];

    }
    cout<<endl;
    }
    return 0;


}

14.字串的连接最长路径查找

看完题目才知道是字符串字典序排序,直接上std::sort也行
不过我用了优先级队列,这样的话复杂度应该低一些。
std::priority_queue需要注意的是模板参数

#include <iostream>
#include <string>
#include <vector>
#include <queue>
using namespace std;
int main()
{
    int n;
    priority_queue<string,vector<string>,greater<string> >q;

    string str;
    while(cin>>n)
    {
    for(int i=0;i<n;++i)
    {
        cin>>str;
        q.push(str);
    }
    while(!q.empty())
    {
        cout<<q.top()<<endl;
        q.pop();
    }
    }
    return 0;
}

15.求int型正整数在内存中存储时1的个数

剑指offer上的题,有一个小小的trick吧,当然直接按位比较也行的

#include <iostream>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
    int count=0;
    while(n)
    {
        n&=(n-1);
        ++count;
    }
    cout<<count<<endl;
    }
}

16.购物单

这应该是前20题里面最耗费我时间的一题了。
改进的0-1背包,先回顾一下0-1背包:
最朴素的0-1背包问题里面,只有拿和不拿两个选项
因此动规方程可以如下写:
dp(i,j)=max(d

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值