迴圈

for do while

for(once;first;third){second}

/*
 * zerojudge
 * b294. 經濟大恐荒
 * C++
 * AC (2ms, 316KB)
*/
#include <bits/stdc++.h>
using namespace std;

int main(){
    int n;
    cin >> n;
    int sum=0;
    for(int i=1;i<=n;i++){ 
        int x;
        cin >> x;
        sum += x*i;
    }
    cout << sum << endl;
    return 0;
}

while(first){second}

/*
 * leetcode
 * 12. Integer to Roman
 * C++
 * AC
 * 4ms Beats 73.65%
 * 7.84MB Beats 95.43%
*/
class Solution {
public:
    string intToRoman(int num) {
        string s="";
        while(num>=1000){
            num-=1000;
            s+="M";
        }
        while(num>=900){
            num-=900;
            s+="CM";
        }
        while(num>=500){
            num-=500;
            s+="D";
        }
        while(num>=400){
            num-=400;
            s+="CD";
        }
        while(num>=100){
            num-=100;
            s+="C";
        }
        while(num>=90){
            num-=90;
            s+="XC";
        }
        while(num>=50){
            num-=50;
            s+="L";
        }
        while(num>=40){
            num-=40;
            s+="XL";
        }
        while(num>=10){
            num-=10;
            s+="X";
        }
        while(num>=9){
            num-=9;
            s+="IX";
        }
        while(num>=5){
            num-=5;
            s+="V";
        }
        while(num>=4){
            num-=4;
            s+="IV";
        }
        while(num>=1){
            num-=1;
            s+="I";
        }
        return s;
    }
};

do{once second}while(first);

Last updated

Was this helpful?