Chinaunix首页 | 论坛 | 博客
  • 博客访问: 197894
  • 博文数量: 36
  • 博客积分: 2501
  • 博客等级: 少校
  • 技术积分: 420
  • 用 户 组: 普通用户
  • 注册时间: 2007-04-18 23:27
个人简介

时间就是一切。

文章分类

全部博文(36)

文章存档

2023年(1)

2017年(2)

2016年(6)

2014年(1)

2009年(1)

2008年(15)

2007年(10)

我的朋友

分类: C/C++

2017-08-13 11:19:29

// 字符串相加.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
#include


#define MIN_a_VALUE 10
#define MIN_z_VALUE 35


/*
0-9
a-z 值 10 - 35
*/
int GetCValue(const char *num)
{
int numL, reValue;


if(NULL == num)
{
return -1;
}


numL=*num;
if(numL>='0' && numL<= '9')
{
numL = numL - '0';//0-9
}
else if(numL>='a' && numL<= 'z')
{
numL = numL - 'W';//a-z 转换到值 10 - 35 之间
}
else
{
numL = 0;
}
return numL;
}


//修正计算结果
int transValue(char *str)
{
int strL=0,index=0, mind=0, swp1, swp2;
char tmpBuf[20]={0};
char *tmpSt=NULL;


if(NULL==str)
{
return -1;
}
strL=strlen(str);
mind=(strL/2);
while(index {
*(str+index) = *(str+index) + *(str+((strL-index)-1));
*(str+((strL-index)-1)) = *(str+index) - *(str+((strL-index)-1));
*(str+index) = *(str+index) - *(str+((strL-index)-1));
index++;
}
return 0;
}




int GetSum(int n, char *num1, char *num2, char *result)
{
int numL1,numL2, sum, tmpValue=0, higBit=0, strL1, strL2;
char numC1,numC2;
char *pTmp=NULL, *transDd=NULL;
bool chage=false;

//进入参数检查
if(0==n || NULL==num1 
|| NULL==num2 || NULL==result)
{
return -1;
}


transDd=result;
//兼容不同长度的 num1 与 num2 相加,取较长的字符串作为计算基准
strL1=strlen(num1);
strL2=strlen(num2);
if(strL1>=strL2)
{
pTmp = num1;
}
else
{
pTmp = num2;
}
strL1=strL1-1;
strL2=strL2-1;
while(*pTmp!='\0')
{
if(strL1<0)
{
numC1=0;
}
else
{
numC1=GetCValue(&num1[strL1]);
}
if(strL2<0)
{
numC2=0;
}
else
{
numC2=GetCValue(&num2[strL2]);
}


sum = (numC1 + numC2) + higBit;
higBit = 0;//低位向高位进位值
if(0==sum/n)
{
//sum 未大于进制不需进位
tmpValue = sum%n;
}
else
{
//sum 大于进制需要进位
sum = sum + higBit;
higBit = sum/n;//进位 higBit
tmpValue = (sum%n);
}
if(tmpValue>= MIN_a_VALUE && tmpValue<= MIN_z_VALUE)
{
//值在10~35 之间用 a~z 表示
tmpValue=tmpValue + 'W';
}
else
{
//值在0~9 之间用 0~9 表示
tmpValue=tmpValue + '0';
}
*result=tmpValue;
result++;
strL1--;
strL2--;
pTmp++;
tmpValue=0;
}
if(0!=higBit)
{
if(higBit>= MIN_a_VALUE && higBit<= MIN_z_VALUE)
{
//值在10~35 之间用 a~z 表示
higBit=higBit + 'W';
}
else
{
//值在0~9 之间用 0~9 表示
higBit=higBit + '0';
}
*result = higBit;
}
transValue(transDd);
return 0;
}




int _tmain(int argc, _TCHAR* argv[])
{
char result[20]={0};


GetSum(16, "abcdef", "af", result);


printf("result = %s\n", result);


return 0;
}

阅读(1084) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~