下面是几个没有怎么做好的题.
1:对于一个数组,每次随机一个下标,移除对应的位置,怎么保证每次随机下标都有内容移除。
在每次移除后,把移除的位置后最后一个位置交换,这样就能保证0-----k都有值,然后随机值%k
2:怎么判断一个数是不是2的幂
int check(int n) { return (n & (n - 1)) == 0; } void solve() { cout << check(10) << " " << check(16) << endl; }
让n-1,然后按位与。
3:列表反转
#include "pch.h" #include <string> #include<iostream> #include <sstream> #include<map> #include<memory.h> #include<vector> #include<algorithm> #include<queue> #include<vector> #include<stack> #include<math.h> #include<iomanip> #include<bitset> #include"math.h" namespace cc { using std::cout; using std::endl; using std::cin; using std::map; using std::vector; using std::string; using std::sort; using std::priority_queue; using std::greater; using std::vector; using std::swap; using std::stack; using std::bitset; using std::stringstream; constexpr int N = 20; constexpr int S = 500; constexpr int MAXR = 2 * N; constexpr int MAXC = 2 * N; int check(int n) { return (n & (n - 1)) == 0; } class Node { public: int val; Node* next; Node(int val,Node* next) :val(val),next(next) { } }; void print(Node* root) { while (root != nullptr) { cout << " " << root->val; root = root->next; } cout << endl; } Node* reverse(Node * root) { if (root == nullptr) return nullptr; Node* head = root; while (root->next) { Node* next = root->next; root->next = next->next; next->next = head; head = next; } return head; } void solve() { Node* n1 = new Node(1, nullptr); Node* n2 = new Node(2, n1); Node* n3 = new Node(3, n2); Node * root = new Node(4, n3); print(root); root = reverse(root); cout << "反转后的------" << endl; print(root); } }; int main() { #ifndef ONLINE_JUDGE freopen("d://1.text", "r", stdin); #endif // !ONLINE_JUDGE cc::solve(); return 0; }
上溢到2的幂和下溢2的幂
int flow(int n) { n = n | n >> 1; n = n | n >> 2; n = n | n >> 4; n = n | n >> 8; n = n | n >> 16; n++; if (n < 0) n = n >> 1;//2的30次幂 return n + 1; } int ceil(int n) { n = flow(n); return n >> 1; }