技巧总结:
1.求int型的MAX,MIN
static const int MAX = (int)((unsigned)~0 >> 1); //32767
static const int MIN = -(int)((unsigned)~0 >> 1) - 1;/-32768
2.常用的变量声明为register
register long acc, cutoff;
register int c=6;
3.奇偶判断
if(x&1==0)偶数
乘法,除法操作
x<<=1//*2
x>>=1// /2
4、代码书写规范
if ( ( p != NULL ) && ( strlen(p) != 0 ))
再比如,一个很长的条件判断:
if ( ( ch[0] >= '0' || ch[0] <= '9' ) &&
( ch[1] >= 'a' || ch[1] <= 'z' ) &&
( ch[2] >= 'A' || ch[2] <= 'Z' ) )
#define MAX( (a), (b) ) (a)>(b)?(a):(b)
typedef short INT16_T;
typedef unsigned short UINT16_T;
typedef int INT32_T;
typedef unsigned int UINT32_T;
#define MAX_USR_CNT 120
for ( i=0; i<MAX_USER_CNT; i++){
....
}
尽量用for而不是while做循环
5、函数书写规范
// test_parenthesis matching.cpp : Defines the entry point for the console application.
/************************************************************************
* 环境:VS2008
* 函数名:parenthesis matching_styles
*
* 函数功能:括号匹配,包括(),[],{}
返回结果:匹配括号的种类
参 数:括号的个数
*
* 创建: 2014/3/20
*
* 版本号:1.0
*
思路:括号匹配有合法有的不合法 如 (()))( 这样就不是合法的匹配样式。
为了避免这种情况的出现,记录当前左括号的个数和右括号的个数,
使右括号的个数不大于左括号的个数。主要思想类似于0-1背包问题,当进行到某一步的时候 有两种方法:放'(' 和 放 ')'
*
************************************************************************
#include "stdafx.h"
#include<iostream>
#include <vector>
using namespace std;
void parenthesis matching_styles(int left,int right,int sum,vector<char> bracket)
{
if ( left == sum && right==sum ) //如果左边和右边都为要匹配的个数,则输出结果
{
vector<char>::iterator iter=bracket.begin();
for ( ;iter!=bracket.end();iter++)
{
cout<<*iter<<' ';
}
cout<<endl;
return ;
}
if (left<=sum)
{
bracket.push_back('('); //放入左括号,然后递归
maching(left+1,right,sum,bracket);
bracket.pop_back(); //递归后弹出左括号
}
if (left>right&&left<=sum)
{
bracket.push_back(')');
maching(left,right+1,sum,bracket);
bracket.pop_back();
}
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<char> bracket; //记录当前的匹配样式
int num;
cin>>num; //输入括号的个数
parenthesis matching_styles(0,0,num,bracket);
return 0;
//Console.ReadKey();
//Console.ReadLine();
getch();
}
6、if 的变形
此例子转载自: 酷 壳 – CoolShell.cn
把条件语句:
1
2
|
if
(data[j] >= 128)
sum += data[j];
|
变成:
1
2
|
int
t = (data[j] - 128) >> 31;
sum += ~t & data[j];
|
关于XOR的方式,参看下面的示例:
或者更为简单的:
相关博客: http://blog.csdn.net/huazhongkejidaxuezpp/article/details/21478889