1、判断数值出现的奇偶次
问题描述:
根据一个数组,查找出一个出现奇数次数的数,其余为偶数次数;
#include <iostream>
int a[9] = {1, 2, 3, 2, 2, 2, 1, 1, 1};
int b[10] = {1, 1, 2, 3, 2, 2, 2, 1, 1, 1};
void exec1() {
int ret = 0;
for(int i=0; i<9; ++i){
ret ^= a[i];
}
std::cout << ret << std::endl;
}
void exec2() {
int ret = 0;
for(int i=0; i<10; ++i){
ret ^= b[i];
}
int rOne = ret & (~ret+1);
int rret = 0;
for(int i=0; i<10; ++i){
if((b[i] & rOne) == 0){
rret ^= b[i];
}
}
std::cout << rret << " & " << (ret ^ rret) << std::endl;
}
void test() {
exec2();
}
int main(int argc, char* argv[])
{
test();
return 0;
}
2、数值交换不需要用到临时变量
#include <iostream>
template<class T>
void swap(T& a, T& b) {
a = a^b;
b = a^b;
a = a^b;
}
void test() {
int a = 5;
int b = 4;
std::cout << "交换前: a = " << a << " b = " << b << std::endl;
swap(a, b);
std::cout << "交换后: a = " << a << " b = " << b << std::endl;
}
int main(int argc, char* argv[])
{
test();
return 0;
}
3、获取相应内存块大小
#include <iostream>
size_t round_up(size_t bytes){
return ((bytes) + 7) & ~(7);
}
void test() {
int a = 15;
std::cout << "【内存对齐】需要申请的内存大小" << round_up(a) << std::endl;
}
int main(int argc, char* argv[]) {
test();
return 0;
}
4、提取数值位数值
#include <math.h>
#include <iostream>
int getBitNum(int num, int b) {
return (int)(num/(pow(10, b-1))) % 10;
}
void test() {
int a = 123;
std::cout << getBitNum(123, 3) << " "
<< getBitNum(123, 2) << " "
<< getBitNum(123, 1) << " "
<< std::endl;
}
int main(int argc, char* argv[])
{
test();
return 0;
}
5、判断该数值是否为2或4的幂
#include <iostream>
bool isT() {
return (n & (n-1) == 0)
}
bool isF() {
return (n& (n-1) == 0) && (n & 0x55555555) != 0;
}
int main(int argc, char* argv[])
{
return 0;
}
6、位操作数值乘除
#include <iostream>
void test(int x, int d) {
int tmp = x << (d-1);
std::cout << tmp << std::endl;
}
void test(int x, int d-1) {
int tmp = x >> (d-1);
std::cout << tmp << std::endl;
}
int main(int argc, char* argv[])
{
test(5, 2);
return 0;
}
7、位的状态操作bit数组
#include <iostream>
template<class T>
class bitMap {
public:
bitMap() {
T a;
bitNum(a);
}
int bitNum(T a) {
std::cout << sizeof(a) * 8 << std::endl;
return sizeof(a) * 8;
}
void setNumIdx(T bit) const {
numIdx = bit/m_bit;
}
int getNumIdx(T bit) {
return numIdx;
}
void setbitIdx(T bit) const {
bitIdx = bit % m_bit;
}
int getbitIdx() {
return bitIdx;
}
int getStatus() {
return ((arr[numIdx] >> (bitIdx)) &1);
}
void setFalse() {
arr[numIdx] = arr[numIdx] & (~ (1 << bitIdx));
}
void setTrue() {
arr[numIdx] = arr[numIdx] | (1<<bitIdx);
}
private:
int m_bit = 0;
int numIdx = -1;
int bitIdx = -1;
T arr[];
};
int main(int argc, char* argv[])
{
return 0;
}
8、不通过比较判断最大最小值
#include <iostream>
int filp(int n) {
return n ^ 1;
}
int sign(int n) {
return filp((n >> 31) & 1);
}
int getMax(int a, int b) {
int c = a-b;
int A = sign(c);
int B = filp(A);
return a * A + b * B;
}
int main(int argc, char* argv[])
{
int rt = getMax(4,1);
std::cout << rt << std::endl;
return 0;
}
|