有趣的二進制 牛客網 java大數的一些方法
阿新 • • 發佈:2018-06-06
ons debug LG c++ 行為 -h 負數 compare ner
鏈接:https://www.nowcoder.com/acm/contest/124/C
來源:牛客網
題目描述
小新在學C語言的時候,鄺老師告訴他double類型的數據在表示小數的時候,小數點後的有效位是有限的,但是沒有告訴他這是為什麽,後來他發現0.1的二進制是一個無限循環小數0.000110011001100110011001100···,如果只取27位小數,再轉換成十進制的話就變成了0.09999999403953552,小新開心的解決了這個問題。與此同時,小新又有了一個新的問題:一個數在64位二進制補碼表示下,一共有多少個1。因為小數有無解的情況,所以我們保證輸入的都是整數。輸入描述:
有多組數據,每一行為一個數字n。
輸出描述:
輸出這個數字在二進制補碼下1的個數。示例1
輸入
復制15
輸出
復制4
開始自己做的時候讀題目不仔細,以為題目沒有給出數的取值範圍,就當成大數來做了,然後幾次wa。
後來看別人的代碼再仔細看題目發現這題目中有說是64位二進制所以直接用unsigned long long 就可以了。
(看別人過的代碼這題目好像不要考慮負數。。)
貼一份c++的再貼兩份java的(java的一些大數方法可以學)
#include<cstdio> #include<cstring> #include<string> #include<iostream> #include<algorithm> #include<cmath> #include<string> #include<map> #define debug(a) cout << #a << ": " << a << endl; using namespace std ; const int maxn = 1e4 + 20 ; typedef unsigned long long ll; int main() { ios::sync_with_stdio(false); ll n; while( cin >> n ) { ll cnt = 0; while( n ) { if( n % 2 == 1 ) { cnt ++; } n /= 2; } cout << cnt << endl; } return 0 ; }
//Java
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); while (cin.hasNextLong()) { long n = cin.nextLong(); System.out.println(Long.bitCount(n)); //可以這樣計算二進制中1的個數 } } }
import java.util.*; import java.math.*; public class Main { public static void main(String args[]) { Scanner cin = new Scanner(System.in); BigInteger a,b,c,d; while(cin.hasNext()) { a=cin.nextBigInteger(); if(a.compareTo(BigInteger.valueOf(0))<0) { a=(BigInteger.valueOf(2).pow(64)).add(a); //valueOf()將其他類型的值轉換成大數 } int s=0; while(a.compareTo(BigInteger.valueOf(0))>0) //大數比較大小,大於0返回1,等於返回0,小於返回-1 { BigInteger x=a.remainder(BigInteger.valueOf(2));//System.out.println(x); if(x.compareTo(BigInteger.valueOf(1))==0) s++; a=a.divide(BigInteger.valueOf(2)); } System.out.println(s); } } }
有趣的二進制 牛客網 java大數的一些方法