codeparrot/xlcost-text-to-code huggingface dataset:
Lexicographic rank of a string | Java program to find lexicographic rank of a string ; A utility function to find factorial of n ; A utility function to count smaller characters on right of arr [ low ] ; A function to find rank of a string in all permutations of characters ; count number of chars smaller than str [ i ] from str [ i + 1 ] to str [ len - 1 ] ; Driver program to test above function
import java . io . * ; import java . util . * ; class GFG { static int fact ( int n ) { return ( n <= 1 ) ? 1 : n * fact ( n - 1 ) ; } static int findSmallerInRight ( String str , int low , int high ) { int countRight = 0 , i ; for ( i = low + 1 ; i <= high ; ++ i ) if ( str . charAt ( i ) < str . charAt ( low ) ) ++ countRight ; return countRight ; } static int findRank ( String str ) { int len = str . length ( ) ; int mul = fact ( len ) ; int rank = 1 ; int countRight ; for ( int i = 0 ; i < len ; ++ i ) { mul /= len - i ; countRight = findSmallerInRight ( str , i , len - 1 ) ; rank += countRight * mul ; } return rank ; } public static void main ( String [ ] args ) { String str = " string " ; System . out . println ( findRank ( str ) ) ; } }
Lexicographic rank of a string | A O ( n ) solution for finding rank of string ; all elements of count [ ] are initialized with 0 ; A utility function to find factorial of n ; Construct a count array where value at every index contains count of smaller characters in whole string ; Removes a character ch from count [ ] array constructed by populateAndIncreaseCount ( ) ; A function to find rank of a string in all permutations of characters ; Populate the count array such that count [ i ] contains count of characters which are present in str and are smaller than i ; count number of chars smaller than str [ i ] fron str [ i + 1 ] to str [ len - 1 ] ; Reduce count of characters greater than str [ i ] ; Driver code
class GFG { static int MAX_CHAR = 256 ; int count [ ] = new int [ MAX_CHAR ] ; static int fact ( int n ) { return ( n <= 1 ) ? 1 : n * fact ( n - 1 ) ; } static void populateAndIncreaseCount ( int [ ] count , char [ ] str ) { int i ; for ( i = 0 ; i < str . length ; ++ i ) ++ count [ str [ i ] ] ; for ( i = 1 ; i < MAX_CHAR ; ++ i ) count [ i ] += count [ i - 1 ] ; } static void updatecount ( int [ ] count , char ch ) { int i ; for ( i = ch ; i < MAX_CHAR ; ++ i ) -- count [ i ] ; } static int findRank ( char [ ] str ) { int len = str . length ; int mul = fact ( len ) ; int rank = 1 , i ; populateAndIncreaseCount ( count , str ) ; for ( i = 0 ; i < len ; ++ i ) { mul /= len - i ; rank += count [ str [ i ] - 1 ] * mul ; updatecount ( count , str [ i ] ) ; } return rank ; } public static void main ( String args [ ] ) { char str [ ] = " string " . toCharArray ( ) ; System . out . println ( findRank ( str ) ) ; } }
Efficient program to calculate e ^ x | Java efficient program to calculate e raise to the power x ; Function returns approximate value of e ^ x using sum of first n terms of Taylor Series ; initialize sum of series ; driver program
import java . io . * ; class GFG { static float exponential ( int n , float x ) { float sum = 1 ; for ( int i = n - 1 ; i > 0 ; -- i ) sum = 1 + x * sum / i ; return sum ; } public static void main ( String [ ] args ) { int n = 10 ; float x = 1 ; System . out . println ( " e ^ x ▁ = ▁ " + exponential ( n , x ) ) ; } }
Measure one litre using two vessels and infinite water supply | Sample run of the Algo for V1 with capacity 3 and V2 with capacity 7 1. Fill V1 : V1 = 3 , V2 = 0 2. Transfer from V1 to V2 , and fill V1 : V1 = 3 , V2 = 3 2. Transfer from V1 to V2 , and fill V1 : V1 = 3 , V2 = 6 3. Transfer from V1 to V2 , and empty V2 : V1 = 2 , V2 = 0 4. Transfer from V1 to V2 , and fill V1 : V1 = 3 , V2 = 2 5. Transfer from V1 to V2 , and fill V1 : V1 = 3 , V2 = 5 6. Transfer from V1 to V2 , and empty V2 : V1 = 1 , V2 = 0 7. Stop as V1 now contains 1 litre . Note that V2 was made empty in steps 3 and 6 because it became full ; A utility function to get GCD of two numbers ; Class to represent a Vessel ; A vessel has capacity , and current amount of water in it ; Constructor : initializes capacity as given , and current as 0 ; The main function to fill one litre in this vessel . Capacity of V2 must be greater than this vessel and two capacities must be coprime ; solution exists iff a and b are co - prime ; fill A ( smaller vessel ) ; Transfer water from V1 to V2 and reduce current of V1 by the amount equal to transferred water ; Finally , there will be 1 litre in vessel 1 ; Fills vessel with given amount and returns the amount of water transferred to it . If the vessel becomes full , then the vessel is made empty ; If the vessel can accommodate the given amount ; If the vessel cannot accommodate the given amount , then store the amount of water transferred ; Since the vessel becomes full , make the vessel empty so that it can be filled again ; Driver program to test above function ; a must be smaller than b ; Create two vessels of capacities a and b ; Get 1 litre in first vessel
class GFG { static int gcd ( int a , int b ) { return b > 0 ? gcd ( b , a % b ) : a ; } static class Vessel { int capacity , current ; public Vessel ( int capacity ) { this . capacity = capacity ; current = 0 ; } void makeOneLitre ( Vessel V2 ) { if ( gcd ( capacity , V2 . capacity ) != 1 ) return ; while ( current != 1 ) { if ( current == 0 ) current = capacity ; System . out . print ( " Vessel ▁ 1 : ▁ " + current + " ▁ Vessel ▁ 2 : ▁ " + V2 . current + "NEW_LINE"); current = current - V2 . transfer ( current ) ; } System . out . print ( " Vessel ▁ 1 : ▁ " + current + " ▁ Vessel ▁ 2 : ▁ " + V2 . current + "NEW_LINE"); } int transfer ( int amount ) { if ( current + amount < capacity ) { current += amount ; return amount ; } int transferred = capacity - current ; current = 0 ; return transferred ; } } public static void main ( String [ ] args ) { int a = 3 , b = 7 ; Vessel V1 = new Vessel ( a ) ; Vessel V2 = new Vessel ( b ) ; V1 . makeOneLitre ( V2 ) ; } }
Random number generator in arbitrary probability distribution fashion | Java program to generate random numbers according to given frequency distribution ; Utility function to find ceiling of r in arr [ l . . h ] ; Same as mid = ( l + h ) / 2 ; The main function that returns a random number from arr [ ] according to distribution array defined by freq [ ] . n is size of arrays . ; Create and fill prefix array ; prefix [ n - 1 ] is sum of all frequencies . Generate a random number with value from 1 to this sum ; Find index of ceiling of r in prefix arrat ; Driver code ; Let us generate 10 random numbers accroding to given distribution
class GFG { static int findCeil ( int arr [ ] , int r , int l , int h ) { int mid ; while ( l < h ) { mid = l + ( ( h - l ) >> 1 ) ; if ( r > arr [ mid ] ) l = mid + 1 ; else h = mid ; } return ( arr [ l ] >= r ) ? l : - 1 ; } static int myRand ( int arr [ ] , int freq [ ] , int n ) { int prefix [ ] = new int [ n ] , i ; prefix [ 0 ] = freq [ 0 ] ; for ( i = 1 ; i < n ; ++ i ) prefix [ i ] = prefix [ i - 1 ] + freq [ i ] ; int r = ( ( int ) ( Math . random ( ) * ( 323567 ) ) % prefix [ n - 1 ] ) + 1 ; int indexc = findCeil ( prefix , r , 0 , n - 1 ) ; return arr [ indexc ] ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int freq [ ] = { 10 , 5 , 20 , 100 } ; int i , n = arr . length ; for ( i = 0 ; i < 5 ; i ++ ) System . out . println ( myRand ( arr , freq , n ) ) ; } }
How to check if a given number is Fibonacci number ? | Java program to check if x is a perfect square ; A utility method that returns true if x is perfect square ; Returns true if n is a Fibonacci Number , else false ; n is Fibonacci if one of 5 * n * n + 4 or 5 * n * n - 4 or both is a perfect square ; Driver method
class GFG { static boolean isPerfectSquare ( int x ) { int s = ( int ) Math . sqrt ( x ) ; return ( s * s == x ) ; } static boolean isFibonacci ( int n ) { return isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ; } public static void main ( String [ ] args ) { for ( int i = 1 ; i <= 10 ; i ++ ) System . out . println ( isFibonacci ( i ) ? i + " ▁ is ▁ a ▁ Fibonacci ▁ Number " : i + " ▁ is ▁ a ▁ not ▁ Fibonacci ▁ Number " ) ; } }
Count trailing zeroes in factorial of a number | Java program to count trailing 0 s in n ! ; Function to return trailing 0 s in factorial of n ; Initialize result ; Keep dividing n by powers of 5 and update count ; Driver Code
import java . io . * ; class GFG { static int findTrailingZeros ( int n ) { int count = 0 ; for ( int i = 5 ; n / i >= 1 ; i *= 5 ) count += n / i ; return count ; } public static void main ( String [ ] args ) { int n = 100 ; System . out . println ( " Count ▁ of ▁ trailing ▁ 0s ▁ in ▁ " + n + " ! ▁ is ▁ " + findTrailingZeros ( n ) ) ; } }
Program for nth Catalan Number |  ; A recursive function to find nth catalan number ; Base case ; catalan ( n ) is sum of catalan ( i ) * catalan ( n - i - 1 ) ; Driver Code
class CatalnNumber { int catalan ( int n ) { if ( n <= 1 ) { return 1 ; } int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { res += catalan ( i ) * catalan ( n - i - 1 ) ; } return res ; } public static void main ( String [ ] args ) { CatalnNumber cn = new CatalnNumber ( ) ; for ( int i = 0 ; i < 10 ; i ++ ) { System . out . print ( cn . catalan ( i ) + " ▁ " ) ; } } }
Program for nth Catalan Number | A dynamic programming based function to find nth Catalan number ; Table to store results of subproblems ; Initialize first two values in table ; Fill entries in catalan [ ] using recursive formula ; Return last entry ; Driver code
class GFG { static int catalanDP ( int n ) { int catalan [ ] = new int [ n + 2 ] ; catalan [ 0 ] = 1 ; catalan [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { catalan [ i ] = 0 ; for ( int j = 0 ; j < i ; j ++ ) { catalan [ i ] += catalan [ j ] * catalan [ i - j - 1 ] ; } } return catalan [ n ] ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < 10 ; i ++ ) { System . out . print ( catalanDP ( i ) + " ▁ " ) ; } } }
Program for nth Catalan Number | Java program for nth Catalan Number ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver code
class GFG { static long binomialCoeff ( int n , int k ) { long res = 1 ; if ( k > n - k ) { k = n - k ; } for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } static long catalan ( int n ) { long c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < 10 ; i ++ ) { System . out . print ( catalan ( i ) + " ▁ " ) ; } } }
Program for nth Catalan Number |  ; Function to print the number ; For the first number C ( 0 ) ; Iterate till N ; Calculate the number and print it ; Driver code ; Function call
import java . util . * ; class GFG { static void catalan ( int n ) { int cat_ = 1 ; System . out . print ( cat_ + " ▁ " ) ; for ( int i = 1 ; i < n ; i ++ ) { cat_ *= ( 4 * i - 2 ) ; cat_ /= ( i + 1 ) ; System . out . print ( cat_ + " ▁ " ) ; } } public static void main ( String args [ ] ) { int n = 5 ; catalan ( n ) ; } }
Find Excel column name from a given column number | Java program to find Excel column name from a given column number ; Function to print Excel column name for a given column number ; To store result ( Excel column name ) ; Find remainder ; If remainder is 0 , then a ' Z ' must be there in output ; If remainder is non - zero ; Reverse the string and print result ; Driver program to test above function
public class ExcelColumnTitle { private static void printString ( int columnNumber ) { StringBuilder columnName = new StringBuilder ( ) ; while ( columnNumber > 0 ) { int rem = columnNumber % 26 ; if ( rem == 0 ) { columnName . append ( " Z " ) ; columnNumber = ( columnNumber / 26 ) - 1 ; } else { columnName . append ( ( char ) ( ( rem - 1 ) + ' A ' ) ) ; columnNumber = columnNumber / 26 ; } } System . out . println ( columnName . reverse ( ) ) ; } public static void main ( String [ ] args ) { printString ( 26 ) ; printString ( 51 ) ; printString ( 52 ) ; printString ( 80 ) ; printString ( 676 ) ; printString ( 702 ) ; printString ( 705 ) ; } }
Find Excel column name from a given column number |  ; Step 1 : Converting to number assuming 0 in number system ; Step 2 : Getting rid of 0 , as 0 is not part of number system ; Driver code
import java . util . * ; class GFG { static void printString ( int n ) { int [ ] arr = new int [ 10000 ] ; int i = 0 ; while ( n > 0 ) { arr [ i ] = n % 26 ; n = n / 26 ; i ++ ; } for ( int j = 0 ; j < i - 1 ; j ++ ) { if ( arr [ j ] <= 0 ) { arr [ j ] += 26 ; arr [ j + 1 ] = arr [ j + 1 ] - 1 ; } } for ( int j = i ; j >= 0 ; j -- ) { if ( arr [ j ] > 0 ) System . out . print ( ( char ) ( ' A ' + arr [ j ] - 1 ) ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { printString ( 26 ) ; printString ( 51 ) ; printString ( 52 ) ; printString ( 80 ) ; printString ( 676 ) ; printString ( 702 ) ; printString ( 705 ) ; } }
Calculate the angle between hour hand and minute hand | Java program to find angle between hour and minute hands ; Function to calculate the angle ; validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; smaller angle of two possible angles ; Driver Code
import java . io . * ; class GFG { static int calcAngle ( double h , double m ) { if ( h < 0 m < 0 h > 12 m > 60 ) System . out . println ( " Wrong ▁ input " ) ; if ( h == 12 ) h = 0 ; if ( m == 60 ) { m = 0 ; h += 1 ; if ( h > 12 ) h = h - 12 ; } int hour_angle = ( int ) ( 0.5 * ( h * 60 + m ) ) ; int minute_angle = ( int ) ( 6 * m ) ; int angle = Math . abs ( hour_angle - minute_angle ) ; angle = Math . min ( 360 - angle , angle ) ; return angle ; } public static void main ( String [ ] args ) { System . out . println ( calcAngle ( 9 , 60 ) + " ▁ degree " ) ; System . out . println ( calcAngle ( 3 , 30 ) + " ▁ degree " ) ; } }
How to check if an instance of 8 puzzle is solvable ? | Java program to check if a given instance of 8 puzzle is solvable or not ; A utility function to count inversions in given array ' arr [ ] ' ; Value 0 is used for empty space ; This function returns true if given 8 puzzle is solvable . ; Count inversions in given 8 puzzle ; return true if inversion count is even . ; Driver code
class GFG { static int getInvCount ( int [ ] [ ] arr ) { int inv_count = 0 ; for ( int i = 0 ; i < 3 - 1 ; i ++ ) for ( int j = i + 1 ; j < 3 ; j ++ ) if ( arr [ j ] [ i ] > 0 && arr [ j ] [ i ] > arr [ i ] [ j ] ) inv_count ++ ; return inv_count ; } static boolean isSolvable ( int [ ] [ ] puzzle ) { int invCount = getInvCount ( puzzle ) ; return ( invCount % 2 == 0 ) ; } public static void main ( String [ ] args ) { int [ ] [ ] puzzle = { { 1 , 8 , 2 } , { 0 , 4 , 3 } , { 7 , 6 , 5 } } ; if ( isSolvable ( puzzle ) ) System . out . println ( " Solvable " ) ; else System . out . println ( " Not ▁ Solvable " ) ; } }
Birthday Paradox | Java program to approximate number of people in Birthday Paradox problem ; Returns approximate number of people for a given probability ; Driver code
class GFG { static double find ( double p ) { return Math . ceil ( Math . sqrt ( 2 * 365 * Math . log ( 1 / ( 1 - p ) ) ) ) ; } public static void main ( String [ ] args ) { System . out . println ( find ( 0.70 ) ) ; } }
Count Distinct Non | Java code to Count Distinct Non - Negative Integer Pairs ( x , y ) that Satisfy the inequality x * x + y * y < n ; This function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; Driver program
import java . io . * ; class GFG { static int countSolutions ( int n ) { int res = 0 ; for ( int x = 0 ; x * x < n ; x ++ ) for ( int y = 0 ; x * x + y * y < n ; y ++ ) res ++ ; return res ; } public static void main ( String args [ ] ) { System . out . println ( " Total ▁ Number ▁ of ▁ distinct ▁ Non - Negative ▁ pairs ▁ is ▁ " + countSolutions ( 6 ) ) ; } }
Count Distinct Non | An efficient Java program to find different ( x , y ) pairs that satisfy x * x + y * y < n . ; This function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; Find the count of different y values for x = 0. ; One by one increase value of x , and find yCount forcurrent x . If yCount becomes 0 , then we have reached maximum possible value of x . ; Add yCount ( count of different possible values of y for current x ) to result ; Increment x ; Update yCount for current x . Keep reducing yCount while the inequality is not satisfied . ; Driver program
import java . io . * ; class GFG { static int countSolutions ( int n ) { int x = 0 , yCount , res = 0 ; for ( yCount = 0 ; yCount * yCount < n ; yCount ++ ) ; while ( yCount != 0 ) { res += yCount ; x ++ ; while ( yCount != 0 && ( x * x + ( yCount - 1 ) * ( yCount - 1 ) >= n ) ) yCount -- ; } return res ; } public static void main ( String args [ ] ) { System . out . println ( " Total ▁ Number ▁ of ▁ distinct ▁ Non - Negative ▁ pairs ▁ is ▁ " + countSolutions ( 6 ) ) ; } }
Program for Method Of False Position | java program for implementation of Bisection Method for solving equations ; An example function whose solution is determined using Bisection Method . The function is x ^ 3 - x ^ 2 + 2 ; Prints root of func ( x ) in interval [ a , b ] ; Initialize result ; Find the point that touches x axis ; Check if the above found point is root ; Decide the side to repeat the steps ; Driver program ; Initial values assumed
import java . io . * ; class GFG { static int MAX_ITER = 1000000 ; static double func ( double x ) { return ( x * x * x - x * x + 2 ) ; } static void regulaFalsi ( double a , double b ) { if ( func ( a ) * func ( b ) >= 0 ) { System . out . println ( " You ▁ have ▁ not ▁ assumed ▁ right ▁ a ▁ and ▁ b " ) ; } double c = a ; for ( int i = 0 ; i < MAX_ITER ; i ++ ) { c = ( a * func ( b ) - b * func ( a ) ) / ( func ( b ) - func ( a ) ) ; if ( func ( c ) == 0 ) break ; else if ( func ( c ) * func ( a ) < 0 ) b = c ; else a = c ; } System . out . println ( " The ▁ value ▁ of ▁ root ▁ is ▁ : ▁ " + ( int ) c ) ; } public static void main ( String [ ] args ) { double a = - 200 , b = 300 ; regulaFalsi ( a , b ) ; } }
Program for Newton Raphson Method | Java program for implementation of Newton Raphson Method for solving equations ; An example function whose solution is determined using Bisection Method . The function is x ^ 3 - x ^ 2 + 2 ; Derivative of the above function which is 3 * x ^ x - 2 * x ; Function to find the root ; x ( i + 1 ) = x ( i ) - f ( x ) / f '(x) ; Driver code ; Initial values assumed
class GFG { static final double EPSILON = 0.001 ; static double func ( double x ) { return x * x * x - x * x + 2 ; } static double derivFunc ( double x ) { return 3 * x * x - 2 * x ; } static void newtonRaphson ( double x ) { double h = func ( x ) / derivFunc ( x ) ; while ( Math . abs ( h ) >= EPSILON ) { h = func ( x ) / derivFunc ( x ) ; x = x - h ; } System . out . print ( " The ▁ value ▁ of ▁ the " + " ▁ root ▁ is ▁ : ▁ " + Math . round ( x * 100.0 ) / 100.0 ) ; } public static void main ( String [ ] args ) { double x0 = - 20 ; newtonRaphson ( x0 ) ; } }
Find the element that appears once | Java code to find the element that occur only once ; Method to find the element that occur only once ; " one ▁ & ▁ arr [ i ] " gives the bits that are there in both ' ones ' and new element from arr [ ] . We add these bits to ' twos ' using bitwise OR ; " one ▁ & ▁ arr [ i ] " gives the bits that are there in both ' ones ' and new element from arr [ ] . We add these bits to ' twos ' using bitwise OR ; The common bits are those bits which appear third time So these bits should not be there in both ' ones ' and ' twos ' . common_bit_mask contains all these bits as 0 , so that the bits can be removed from ' ones ' and ' twos ' ; Remove common bits ( the bits that appear third time ) from ' ones ' ; Remove common bits ( the bits that appear third time ) from ' twos ' ; Driver method
class GFG { static int getSingle ( int arr [ ] , int n ) { int ones = 0 , twos = 0 ; int common_bit_mask ; for ( int i = 0 ; i < n ; i ++ ) { twos = twos | ( ones & arr [ i ] ) ; ones = ones ^ arr [ i ] ; common_bit_mask = ~ ( ones & twos ) ; ones &= common_bit_mask ; twos &= common_bit_mask ; } return ones ; } public static void main ( String args [ ] ) { int arr [ ] = { 3 , 3 , 2 , 3 } ; int n = arr . length ; System . out . println ( " The ▁ element ▁ with ▁ single ▁ occurrence ▁ is ▁ " + getSingle ( arr , n ) ) ; } }
Find the element that appears once | Java code to find the element that occur only once ; Initialize result ; Iterate through every bit ; Find sum of set bits at ith position in all array elements ; The bits with sum not multiple of 3 , are the bits of element with single occurrence . ; Driver method
class GFG { static final int INT_SIZE = 32 ; static int getSingle ( int arr [ ] , int n ) { int result = 0 ; int x , sum ; for ( int i = 0 ; i < INT_SIZE ; i ++ ) { sum = 0 ; x = ( 1 << i ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & x ) == 0 ) sum ++ ; } if ( ( sum % 3 ) != 0 ) result |= x ; } return result ; } public static void main ( String args [ ] ) { int arr [ ] = { 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 } ; int n = arr . length ; System . out . println ( " The ▁ element ▁ with ▁ single ▁ occurrence ▁ is ▁ " + getSingle ( arr , n ) ) ; } }
Detect if two integers have opposite signs | Java Program to Detect if two integers have opposite signs . ; Function to detect signs ; Driver Code
class GFG { static boolean oppositeSigns ( int x , int y ) { return ( ( x ^ y ) < 0 ) ; } public static void main ( String [ ] args ) { int x = 100 , y = - 100 ; if ( oppositeSigns ( x , y ) == true ) System . out . println ( " Signs ▁ are ▁ opposite " ) ; else System . out . println ( " Signs ▁ are ▁ not ▁ opposite " ) ; } }
Count total set bits in all numbers from 1 to n | A simple program to count set bits in all numbers from 1 to n . ; Returns count of set bits present in all numbers from 1 to n ; initialize the result ; A utility function to count set bits in a number x ; Driver program
class GFG { static int countSetBits ( int n ) { int bitCount = 0 ; for ( int i = 1 ; i <= n ; i ++ ) bitCount += countSetBitsUtil ( i ) ; return bitCount ; } static int countSetBitsUtil ( int x ) { if ( x <= 0 ) return 0 ; return ( x % 2 == 0 ? 0 : 1 ) + countSetBitsUtil ( x / 2 ) ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . print ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ " ) ; System . out . print ( countSetBits ( n ) ) ; } }
Count total set bits in all numbers from 1 to n |  ; ans store sum of set bits from 0 to n ; while n greater than equal to 2 ^ i ; This k will get flipped after 2 ^ i iterations ; change is iterator from 2 ^ i to 1 ; This will loop from 0 to n for every bit position ; When change = 1 flip the bit ; again set change to 2 ^ i ; increment the position ; Driver program
public class GFG { static int countSetBits ( int n ) { int i = 0 ; int ans = 0 ; while ( ( 1 << i ) <= n ) { boolean k = false ; int change = 1 << i ; for ( int j = 0 ; j <= n ; j ++ ) { if ( k == true ) ans += 1 ; else ans += 0 ; if ( change == 1 ) { k = ! k ; change = 1 << i ; } else { change -- ; } } i ++ ; } return ans ; } public static void main ( String [ ] args ) { int n = 17 ; System . out . println ( countSetBits ( n ) ) ; } }