Skip to content

Lab6 Best Practice #3

Description

@junyuanjun
/**
 * Created by junyuan on 23/10/2016.
 */
public class Lab6Solution {

    /** Returns the result of comparing 2 big numbers.
     *  Returns true if the numbers are equal.
     *  @param a    a char array consist of '0'..'9'
     *  @param b    a char array consist of '0'..'9'
     * */
    public static int compare(char[] a, char[] b) {
        String aStr = new String(a);
        String bStr = new String(b);

        // 处理前置0
        int index = 0;
        while (index < a.length && a[index] == '0') {
            index++;
        }
        aStr = aStr.substring(index);

        index = 0;
        while (index < b.length && b[index] == '0') {
            index++;
        }
        bStr = bStr.substring(index);

        // 先从长度判断大小
        if (aStr.length() > bStr.length()) {
            return 1;
        } else if (aStr.length() < bStr.length()) {
            return -1;
        }

        // 同样长度的数再一位一位开始比较
        return aStr.compareTo(bStr);
    }

    public static int compare(int[][] a, int[][] b) {
        int aSum = 0;
        int bSum = 0;

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[0].length; j++) {
                aSum += a[i][j];
            }
        }

        for(int i = 0; i < b.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                bSum += b[i][j];
            }
        }

        if (aSum > bSum)
            return 1;
        else if (aSum < bSum)
            return  -1;
        else return 0;
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions