c++问题,输入一个整数,求s的值

请用while编程

问题:

读入整数k

求和S=1+2+4+8+16+……n

期中n是满足规律的且不大于k的最大整数。输出总和s

输入样例:
10
输出样例:
15

有用请采纳

#include<iostream>
using namespace std;

int main(){
    int k, n, S; 
    cin >> k;
    n = 1;  S = 0;
    
    while (n <= k){
        S += n;
        n *= 2;
    }
    
    cout << S << endl;
}