LeetCode 165 Compare Version Numbers
2015-12-04 14:04
288 查看
题目描述
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:
[code]0.1 < 1.1 < 1.2 < 13.37
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
分析
比较字符串版本号大小。把字符串按照’.’分隔成字符串数组v1,v2
因为字符串数组v1,v2的长度可能不一样,要前端对齐,较短的字符串数组变长,后面为null
分别对每一个数进行比较
本来以为这道题会有,字符串转成int溢出的问题,结果没考虑这个问题也AC了~ ^_^
代码
[code] public static int compareVersion(String version1, String version2) { String[] v1 = version1.split("\\."); String[] v2 = version2.split("\\."); int m = Math.max(v1.length, v2.length); v1 = Arrays.copyOf(v1, m); v2 = Arrays.copyOf(v2, m); for (int i = 0; i < m; i++) { int n1 = 0; int n2 = 0; if (v1[i] != null) { n1 = Integer.valueOf(v1[i]); } if (v2[i] != null) { n2 = Integer.valueOf(v2[i]); } if (n1 < n2) { return -1; } else if (n1 > n2) { return 1; } } return 0; }
相关文章推荐
- 游戏名词解释
- Java简介及开发配置
- spring 事务疑惑
- memcache所需要的jar包
- 前端面试题
- jquery等待效果示例
- hadoop RPC协议之WritableRpcEngine
- Centos配置国内yum源
- 技术人员最常用技术网站
- Unity3D中的预制件(Prefab)的创建和使用说明!!!
- Centos配置国内yum源
- BZOJ1039 : [ZJOI2008]无序运动Movement
- 微信公众平台开发(一)两种数据格式
- ORA-65085: cannot open pluggable database in read-only mode问题解决
- iOS开发笔记
- mvn不是内部或外部命令
- storyboard开发指南(1)简介
- Cocos2d-x中__Dictionary,SQLite数据处理
- Maven Clean 编译内存溢出
- 配置参数优化