1,输入N, 打印 N*N螺旋矩阵
比如 N = 3,打印:
1 2 3
8 9 4
7 6 5
N = 4,打印:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
*
* @author phinecos
* @since 2005-05-27
*/
public class test
{
private static int n;
private static int[][] array;
private static int current = 1;
public static void fill(int m)
{
if (current >= n*n)
{//递归结束条件
return;
}
int i;
//上
for (i = n-m; i < m; ++i)
{
array[n-m][i] = current++;
}
//右
for (i = n-m+1; i < m-1; ++i)
{
array[i][m-1] = current++;
}
//下
for (i = m-1; i >= n-m; --i)
{
array[m-1][i] = current++;
}
//左
for (i = m-2; i >= n-m+1; --i)
{
array[i][n-m] = current++;
}
//进入下一层
fill(m-1);
}
public static void main(String[] args) throws Exception
{
n = 10;
array = new int [n][n];
fill(n);
if (n%2 == 1)
{//奇数层次,补充中心点
array[n/2][n/2] = n*n;
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
System.out.print(array[i][j]);
System.out.print('\t');
}
System.out.println();
}
}
}
2,要求:不申请变量和空间反转字符串,用一个函数实现。
第一种解法就是不使用变量交换两个数的两种方法
{//不申请变量和空间反转字符串
if (srcStr == NULL || strlen(srcStr) == 0)
{
return NULL;
}
if (strlen(srcStr) == 1)
return srcStr;
for (int i = 0,j = strlen(srcStr)-1; i < j ; ++i,--j)
{
//第一种交换方式,可能会溢出
//srcStr[i] = srcStr[i] + srcStr[j];
//srcStr[j] = srcStr[i] - srcStr[j];
//srcStr[i] = srcStr[i] - srcStr[j];
//第二种交换方式,可能会溢出
srcStr[i] = srcStr[i] ^ srcStr[j];
srcStr[j] = srcStr[i] ^ srcStr[j];
srcStr[i] = srcStr[i] ^ srcStr[j];
}
return srcStr;
}
第二种方法就是利用空闲的’\0’字符占的位置作为中间变量,最后填补一个’\0’
{//不申请变量和空间反转字符串
if (srcStr == NULL || strlen(srcStr) == 0)
{
return NULL;
}
if (strlen(srcStr) == 1)
return srcStr;
for (int i = 0,j = strlen(srcStr)-1; i <= j ; ++i,--j)
{
srcStr[len] = srcStr[i];
srcStr[i] = srcStr[j];
srcStr[j] = srcStr[len];
}
srcStr[len] = '\0';
return srcStr;
}
3,把一个32位的数按位反转
unsigned int bit_reverse(unsigned int n)
{
n =((n >> 1)& 0x55555555)|((n << 1)& 0xaaaaaaaa);
n =((n >> 2)& 0x33333333)|((n << 2)& 0xcccccccc);
n =((n >> 4)& 0x0f0f0f0f)|((n << 4)& 0xf0f0f0f0);
n =((n >> 8)& 0x00ff00ff)|((n << 8)& 0xff00ff00);
n =((n >> 16)& 0x0000ffff)|((n << 16)& 0xffff0000);
return n;
}
4,将给定的一个整数转换成字符串
{
int count = 0;
bool isNegative = false;
if (num < 0)
{
num = -1 * num;
isNegative = true;
++count;
}
int tmp = num;
while (tmp != 0)
{
++count;
tmp /= 10;
}
char* result = new char[count+1];
if (isNegative == true)
{
result[0] = '-';
}
int i = count;
while (num != 0)
{
result[--i] = num % 10 + '0';
num /= 10;
}
result[count] = '\0';
return result;
}