求int型正整數(shù)在內(nèi)存中存儲時1的個數(shù)
題目描述
輸入一個int型的正整數(shù),計算出該int型數(shù)據(jù)在內(nèi)存中存儲時1的個數(shù)。
輸入描述:
輸入一個整數(shù)(int類型)
輸出描述:
這個數(shù)轉(zhuǎn)換成2進(jìn)制后,輸出1的個數(shù)
示例
輸入:5
輸出:2
#include<iostream>
using namespace std;
int main()
{
int n;
while (cin >> n) {
int ret = 0;
while (n) {
if ((n & 1) == 1)
ret++;
n = n >> 1;
}
cout << ret<< endl;
}
}
取近似值
題目描述
寫出一個程序,接受一個正浮點數(shù)值,輸出該數(shù)值的近似整數(shù)值。如果小數(shù)點后數(shù)值大于等于5,向上取整;小于5,則向下取整。
輸入描述:
輸入一個正浮點數(shù)值
輸出描述:
輸出該數(shù)值的近似整數(shù)值
示例
輸入:5.5
輸出:6
#include<iostream>
#include<string>
using namespace std;
int main() {
string num;
while (cin >> num)
{
size_t pos = num.find('.');
string str = num.substr(0, pos);
int ret = atoi(str.c_str());
if (num[pos + 1] >= '5' && num[pos + 1] < '9')
cout << ret + 1 << endl;
else
cout << ret << endl;
}
}
求最小公倍數(shù)
題目描述
正整數(shù)A和正整數(shù)B 的最小公倍數(shù)是指 能被A和B整除的最小的正整數(shù)值,設(shè)計一個算法,求輸入A和B的最小公倍數(shù)。
輸入描述:
輸入兩個正整數(shù)A和B。
輸出描述:
輸出A和B的最小公倍數(shù)。
/*
最小公倍數(shù) = 兩數(shù)之積除以最大公約數(shù)
*/
#include<iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
if (b>a)
swap(a, b);
int ret = a*b;
int num = a%b;
while (num)
{
a = b;
b = num;
num = a%b;
}
cout << ret / b << endl;
return 0;
}