1. 程式人生 > >華為補招筆試題20171130

華為補招筆試題20171130

blog == mage alt out 類型 swa swap ios

技術分享圖片技術分享圖片技術分享圖片技術分享圖片

註:實現時無需考慮不合法的情況。

解答過程:感覺沒有問題,可後來通過率才37.5%,puzzle。

#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>

//轉化為大寫
string strToUpper(string &str)
{
    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] >= 97)
        {
            str[i] 
-= 32; } } return str; } int main() { string strOrder, strNum; cin >> strOrder >> strNum; int i = 0; vector<string> vecstrNum;//用於存放逗號之間的整數字符串 string strTemNum; //把逗號之間的整數字符串選出來,並放到vecstrNum中 while (i < strNum.size()) { if (strNum[i] !=
,) { strTemNum.push_back(strNum[i]); } else { vecstrNum.push_back(strTemNum); strTemNum.clear(); } i++; if (i == strNum.size()) { vecstrNum.push_back(strTemNum); } } for
(int j = 0; j < vecstrNum.size(); j++) { //對每個整數字符串內部進行升序排序 sort(vecstrNum[j].begin(), vecstrNum[j].end()); //把第一位是0的進行處理,和後面首個不為0的數字進行交換 if (vecstrNum[j][0] == 0) { for (int i = 1; i < vecstrNum[j].size(); i++) { if (vecstrNum[j][i] != 0) { swap(vecstrNum[j][0], vecstrNum[j][i]); break; } } } } //需要把整數字符串轉化為long類型或者int類型,因為string比較大小和數字類型比較大小不一致.比如33和111,字符串類型認為前者大. vector<long> vecIntNum; for (int j = 0; j < vecstrNum.size(); j++) { long num = 0; for (int i = 0; i < vecstrNum[j].size(); i++) { num += pow(10, vecstrNum[j].size() - i - 1)*(vecstrNum[j][i] - 0);//註意減去‘0‘ } vecIntNum.push_back(num); } if (strToUpper(strOrder) == "ASCE") { sort(vecIntNum.begin(), vecIntNum.end()); for (int j = 0; j < vecstrNum.size() - 1; j++) { cout << vecIntNum[j] << ,; } cout << vecIntNum[vecIntNum.size() - 1]; } else//如果是降序就可以倒序輸出. { sort(vecIntNum.begin(), vecIntNum.end()); for (int j = vecIntNum.size() - 1; j > 0; j--) { cout << vecIntNum[j] << ,; } cout << vecIntNum[0]; } return 0; }

華為補招筆試題20171130