1. 程式人生 > >【leetcode】13. Roman to Integer(C)

【leetcode】13. Roman to Integer(C)

題目連結

提交程式碼:

int romanToInt(char* s) {
  int i,p = 0,numslen=0;
	int sum = 0;
	int* nums = (int*)malloc(30 * sizeof(int));

	while (s[p] != '\0')
	{
		if (s[p] == 'M')
			nums[p] = 1000;
		else if (s[p] == 'D')
			nums[p] = 500;
		else if (s[p] == 'C')
			nums[p] = 100;
		else if (s[p] == 'L')
			nums[p] = 50;
else if (s[p] == 'X') nums[p] = 10; else if (s[p] == 'V') nums[p] = 5; else if (s[p] == 'I') nums[p] = 1; p++; } numslen=p; for (i = 0; i < numslen; i++) { //如果前一個數大於當前數,說明當前數是要減的 if (nums[i + 1] > nums[i]) sum -= nums[i]; else sum += nums[i]; } return sum; }

執行結果:

在這裡插入圖片描述