aboutsummaryrefslogtreecommitdiff
path: root/largest_number.c
blob: 2d797f8e585909f93d1e23e5cfdecacbbdadc7bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// 179. Largest Number
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * given a list of non-negative integers 'nums', arrange them such that they
 * form the larget number and return it. since the result may be very large, so
 * you need to return a string instead of an integer.
 */

int check_digit(int val) {
  int digit = 0;
  while (val) {
    digit++;
    val /= 10;
  }
  return digit;
}

char *int_to_str(int val) {
  if (!val)
    return "0";
  int digit = check_digit(val);
  char *res = malloc(digit + 1);
  res[digit] = '\0';
  int idx = digit - 1;
  while (val) {
    res[idx] = val % 10 + '0';
    val /= 10;
    idx--;
  }
  return res;
}

int cmp(const void *a, const void *b) {
  char *aa = *(char **)a;
  char *bb = *(char **)b;
  int n = strlen(aa) + strlen(bb);
  char *ab = malloc(n + 1), *ba = malloc(n + 1);
  ab[n] = '\0';
  ba[n] = '\0';
  strcpy(ab, aa);
  strcpy(&ab[strlen(aa)], bb);
  strcpy(ba, bb);
  strcpy(&ba[strlen(bb)], aa);
  for (int i = 0; i < n; i++) {
    if (ab[i] == ba[i])
      continue;
    return ba[i] - ab[i];
  }
  return 0;
}

char *largestNumber(int *nums, int nums_size) {
  int n = nums_size, len = 0;
  char **data = malloc(n * sizeof(char *));
  bool zero = true;
  for (int i = 0; i < n; i++) {
    data[i] = int_to_str(nums[i]);
    len += strlen(data[i]);
    if (nums[i])
      zero = false;
  }
  if (zero)
    return "0";
  qsort(data, n, sizeof(char *), cmp);
  char *ans = malloc(len + 1);
  int p = 0;
  for (int i = 0; i < n; i++) {
    strcpy(&ans[p], data[i]);
    p += strlen(data[i]);
  }
  return ans;
}

int main() {
  int n1[] = {10, 2}, n2[] = {3, 30, 34, 5, 9};
  printf("%s\n", largestNumber(n1, 2)); // expect: 210
  printf("%s\n", largestNumber(n2, 5)); // expect: 9534330
}