Compare Version Numbers

Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37
分析题目:求版本号大小,

题意: 题意很清晰,就是比较“版本号”大小,给定的版本号version1和version2是字符串类型的,当version1>version2的时候,返回1,反之返回-1。

解题思路:字符串从左向右依次遍历,除过字符串的‘.’,其他的字符转换为十进制,两个版本进行比较,这样利用strtol函数就特别方便,

long int strtol ( const char * str, char ** endptr, int base );
 
从str指向的字符开始转化,忽略掉前面的空格,遇到错误无法转换的字符则返回,如果endptr不为空,则将该字符存储在endptr里。
对前两个函数,base则表示其进制。若进行一次比较之后,没有分出大小(eg.10.2 和10.3)字符串的地址转为‘.’之后的首字母地址进行下一串有效字符的比较。
具体代码如下:
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;
 int compareVersion(string version1, string version2) ;

void main()
{
	string a="10.1.5",b="10.2";
	 cout<<compareVersion(a, b) ;

}
 int compareVersion(string version1, string version2) 
 {
	 int result = 0;
	 char *p1=new char[version1.size()+1];
	 char *p2=new char[version2.size()+1];
	 p1=strcpy(p1,version1.c_str());
	 p2 =strcpy(p2,version2.c_str());
	 while (result == 0 && (*p1 != '\0' || *p2 != '\0')) {
		 long v1,v2;
		 if (*p1=='\0')
		 {
			 v1=0;
		 }
		 else
		 {
			 v1=strtol(p1, &p1, 10);
		 }
		 if (*p2=='\0')
		 {
			 v2=0;
		 }
		 else
		 {
			 	 v2=strtol(p2, &p2, 10);
		 }
		/* long v1 = *p1 == '\0' ? 0 : strtol(p1, &p1, 10);
		 long v2 = *p2 == '\0' ? 0 : strtol(p2, &p2, 10);*/
		 if (v1 > v2) result = 1;
		 else if (v2 > v1) result = -1;
		 else {
			 if (*p1 != '\0') p1++;
			 if (*p2 != '\0') p2++;
		 }
	 }        

	 return result;
 }

结果为 -1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值