题目
题目链接:
https://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7
思路
字符串用.分割为数组,然后依次比较大小
Java代码
import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** 比较版本号* @param version1 string字符串* @param version2 string字符串* @return int整型*/public int compare (String version1, String version2) {//直接看代码,不难看懂String s1[] = version1.split("\\.");String s2[] = version2.split("\\.");int n1 = s1.length;int n2 = s2.length;int n = Math.max(n1, n2);int arr1[] = new int[n];for (int i = 0; i < s1.length; i++) {arr1[i] = Integer.valueOf(s1[i]);}int arr2[] = new int[n];for (int i = 0; i < s2.length ; i++) {arr2[i] = Integer.valueOf(s2[i]);}for (int i = 0; i < n ; i++) {if (arr1[i] > arr2[i]) return 1;else if (arr1[i] < arr2[i]) return -1;}return 0;}
}
Go代码
package mainimport ("strings""strconv"
)/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** 比较版本号* @param version1 string字符串* @param version2 string字符串* @return int整型*/
func compare(version1 string, version2 string) int {// write code heres1 := strings.Split(version1, ".")s2 := strings.Split(version2, ".")n1 := len(s1)n2 := len(s2)n := n1if n < n2 {n = n2}arr1 := make([]int, n)arr2 := make([]int, n)for i := 0; i < n1; i++ {tmp, _ := strconv.Atoi(s1[i])arr1[i] = tmp}for i := 0; i < n2; i++ {tmp, _ := strconv.Atoi(s2[i])arr2[i] = tmp}for i := 0; i < n; i++ {if arr1[i] > arr2[i] {return 1} else if arr1[i] < arr2[i] {return -1}}return 0
}
PHP代码
<?php/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** 比较版本号* @param version1 string字符串 * @param version2 string字符串 * @return int整型*/
function compare( $version1 , $version2 )
{// write code here$s1=explode(".",$version1);$s2 = explode(".",$version2);$n1 = count($s1);$n2= count($s2);$n = $n1;if($n<$n2){$n = $n2;}$arr1 = [];$arr2 = [];for($i=0;$i<$n;$i++){if($i<$n1){$arr1[$i] = intval($s1[$i]);}else{$arr1[$i] =0;$arr2[$i] =0;}}for($i=0;$i<$n2;$i++){$arr2[$i] = intval($s2[$i]);}for($i=0;$i<$n;$i++){if($arr1[$i] > $arr2[$i]) return 1;if($arr1[$i] < $arr2[$i]) return -1;}return 0;
}
C++代码
class Solution {public:/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** 比较版本号* @param version1 string字符串* @param version2 string字符串* @return int整型*/int compare(string version1, string version2) {// write code herevector<int> s1;vector<int> s2;int cur=0;for(int i=0;i<version1.length();i++){if(version1[i]!='.'){cur=cur*10+(version1[i]-48);}else{s1.push_back(cur);cur=0;}}s1.push_back(cur);cur=0;for(int i=0;i<version2.length();i++){if(version2[i]!='.'){cur=cur*10+(version2[i]-48);}else{s2.push_back(cur);cur=0;}}s2.push_back(cur);int n1 = s1.size();int n2 = s2.size();if(n1< n2){int diff = n2-n1;while (diff>0){s1.push_back(0);diff--;}}else if(n1>n2){int diff = n1-n2;while (diff>0){s2.push_back(0);diff--;}}for(int i=0;i<s1.size();i++){cout << s1[i] << ","<< s2[i] << endl;}for(int i=0;i<s1.size();i++){if(s1[i]> s2[i]) return 1;if(s1[i]<s2[i]) return -1;}return 0;}
};