您的位置:首页 > 其它

【LeetCode】Best Time to Buy and Sell Stock II &&Integer to Roman

2014-07-11 15:42 459 查看
1.Best Time to Buy and Sell Stock II 

简单贪心,注意边界条件以及输入是否合法

public class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0)
return 0;
int sum=0;
int i=0;
int j=0;
while(i<prices.length-1)
{
if(prices[i]>=prices[i+1])
{
sum+=prices[i]-prices[j];
j=i+1;
}
i++;
}
sum+=prices[i]-prices[j];
return sum;
}
}

2.Integer to Roman
简单题,分别把千百十个位转换成对应的字符串

public class Solution {
public String intToRoman(int num) {
String s = "";
while (num >= 1000) {
s += "M";
num = num - 1000;
}

if (num >= 900) {
s += "CM";
num = num - 900;
} else {
if (num >= 500) {
s += "D";
num = num - 500;
} else if (num >= 400) {
s += "CD";
num = num - 400;
}
while (num >= 100) {
s += "C";
num = num - 100;
}
}

if (num >= 90) {
s += "XC";
num = num - 90;
} else {
if (num >= 50) {
s += "L";
num = num - 50;
} else if (num >= 40) {
s += "XL";
num = num - 40;
}
while (num >= 10) {
s += "X";
num = num - 10;
}
}

if (num >= 9) {
s += "IX";
num = num - 9;
} else {
if (num >= 5) {
s += "V";
num = num - 5;
} else if (num >= 4) {
s += "IV";
num = num - 40;
}
while (num >= 1) {
s += "I";
num = num - 1;
}
}

return s;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: