一、描述
描述
输入一个 int 型的正整数,计算出该 int 型数据在内存中存储时 1 的个数。
数据范围:保证在 32 位整型数字范围内
输入描述:
输入一个整数(int类型)
输出描述:
这个数转换成2进制后,输出1的个数
示例1
输入:
5
输出:
2
示例2
输入:
0
输出:
0
二、解题
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HJ15_TenToTwo1Number
{
class Program
{
/*
* 十转二再算1的个数
*/
public static void Main(string[] args)
{
string line = string.Empty;
while ((line = Console.ReadLine()) != null)
{
int n = Convert.ToInt32(line);
string s = Convert.ToString(n, 2);
int count = 0;
// 遍历
//foreach (char c in s)
//{
// if (c == '1')
// {
// count++;
// }
//}
count = s.Split('1').Length - 1;
// 光知道split可以字符串调用按照给的分隔符切割字符串转成数组
// 但是转成的长度怎么算呢,101按照1切割居然开头结尾都是空的 很有意思
// 还有个用replace将0换位空输出长度的,也很有意思,复习在写一遍
//string[] str = s.Split('1');
//foreach (string c in str)
//{
// Console.WriteLine(c);
//}
Console.WriteLine(count);
}
}
}
}
三、总结
1.split函数不熟悉,要想办法写程序验证下