华为上机题汇总(十三)

    xiaoxiao2025-08-17  1

    华为上机题汇总(十三)

    注:编译环境为Visual Studio 2012,答案仅供参考。

    目录

    华为上机题汇总十三 目录第六十一题第六十二题第六十三题第六十四题第六十五题

    第六十一题

    61.给一个数组,输出数组里超出所有元素平均值的元素的个数。比如:1、2、3、4、5,输出3.

    #include <iostream> using namespace std; int overAvg(int a[],int n){ int sum = 0, count = 0; for (int i = 0; i < n; i++) { sum += a[i]; } int avg = sum / n; for (int i = 0; i < n; i++) { if (a[i] >= avg || (a[i] == avg && left == 0)) { count++; } } return count; } int main() { int a[] = {1,2,3,4,5}; cout << overAvg(a,5) << endl; return 0; }

    第六十二题

    62.逆序链表输出。 题目描述: 将输入的一个单向链表,逆序后输出链表中的值。链表定义如下: typedef struct tagListNode { int value; struct tagListNode *next; }ListNode;

    要求实现函数: void converse(ListNode **head); 【输入】head: 链表头节点,空间已经开辟好 【输出】head: 逆序后的链表头节点 【返回】无 【注意】只需要完成该函数功能算法,中间不需要有任何IO 的输入输出

    #include <stack> typedef struct tagListNode { int value; struct tagListNode *next; }ListNode; void converse(ListNode **head){ if (!head || !*head) { return; } ListNode *p = *head; stack<ListNode*> s; while (p != NULL){ s.push(p); p = p->next; } *head = s.top(); p = s.top(); s.pop(); while (!s.empty()) { p->next = s.top(); p = p->next; s.pop(); } p->next = NULL; }

    第六十三题

    63.给定一个字符串,实现一个函数,按下述方式输出字符串: * 如果此字符的下一个字符和此字符不一样,原样输出此字符, * 否则先输出此字符,再输出此字符连续出现的次数(次数不大于9)。 * 例如,字符串ABBCCCDEDFFF,输出的结果为AB2C3DEDF3。 * * 不用考虑溢出问题,不能使用任何I/O函数

    #include <string> using namespace std; void convert(const string &s1, string &s2){ auto begin = s1.begin(); while (begin != s1.end()) { auto ahead = begin + 1; if (*ahead != *begin) { s2.push_back(*begin); begin++; continue; } while (ahead != s1.end() && *ahead == *begin) { ahead++; } int n = (ahead - begin) > 9 ? 9 : ahead - begin; s2.push_back(*begin); s2.push_back(n + '0'); begin = ahead; } }

    第六十四题

    64.找出一个数组中满足2^N的元素

    inline bool isRight(int n){ return !(n & (n-1)); } void print2(int a[], int n){ for (int i = 0; i < n; i++) { if (isRight(a[i])) { cout << a[i] << " "; } } }

    第六十五题

    65.查找字符串中空格分隔的单词的最大长度

    #include <iostream> #include <string> using namespace std; int maxLength(const string &s){ int max = 0; auto begin = s.begin(); while (begin != s.end()) { if (*begin == ' ') { begin++; continue; } auto ahead = begin + 1; while (ahead != s.end() && *ahead != ' ') { ahead++; } int length = ahead - begin; if (length > max) { max = length; } begin = ahead; } return max; } int main() { string s; getline(cin,s); cout << maxLength(s) << endl; return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-1301826.html
    最新回复(0)